Convert vector {1,2,3} into string “1-2-3” AS DIGITS

后端 未结 3 588
北恋
北恋 2020-12-22 01:11

I want to display numbers in a std::vector on a screen, but on its way to the recipient, I need to stuff these numbers into a std::st

相关标签:
3条回答
  • 2020-12-22 01:21

    Yet, another example:

    std::vector<unsigned char> v{1,2,3};
    
    std::ostringstream str;
    std::transform(v.begin(), v.end(), std::ostream_iterator<char>(str, "-"), [](unsigned char c){ return '0' + c;});
    
    std::cout << str.str();
    

    [edit]

    unfortunately above will add additional trailing - symbol, to prevent it - more complicated code is necessary:

    std::transform(v.begin(), v.end(), std::ostream_iterator<std::string>(str), [&](auto c){
        return (str.rdbuf()->in_avail() ? "-" : "") + std::to_string(c);
    });
    
    0 讨论(0)
  • 2020-12-22 01:41

    Here is how I handle that:

    std::vector<unsigned char> v {1, 2, 3};
    
    std::string s; // result
    
    auto sep = ""; // continuation separator
    for(auto n: v)
    {
        s += sep + std::to_string(n);
        sep = "-"; // change the continuation separator after first element
    }
    
    std::cout << s << '\n';
    

    The continuation separator starts out empty and gets changed after concatenating the first output.

    Output:

    1-2-3
    
    0 讨论(0)
  • 2020-12-22 01:44

    Simply use a std::ostringstream:

    std::vector<unsigned char> v{1,2,3};
    std::ostringstream oss;
    bool first = true;
    for(auto x : v) {
        if(!first) oss << '-'; 
        else first = false;
        oss << (unsigned int)x;
    }
    std::cout << oss.str() << std::endl;
    
    0 讨论(0)
提交回复
热议问题