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

后端 未结 3 594
北恋
北恋 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 v{1,2,3};
    
    std::ostringstream str;
    std::transform(v.begin(), v.end(), std::ostream_iterator(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(str), [&](auto c){
        return (str.rdbuf()->in_avail() ? "-" : "") + std::to_string(c);
    });
    

提交回复
热议问题