Is there a way to implement analog of Python's 'separator'.join() in C++?

后端 未结 6 620
傲寒
傲寒 2021-02-07 03:44

All I\'ve found is boost::algorithm::string::join. However, it seems like overkill to use Boost only for join. So maybe there are some time-tested recipes?

<
6条回答
  •  温柔的废话
    2021-02-07 04:18

    C++ strings are implemented efficiently.

    std::string s = s1 + s2 + s3;
    

    This could be faster:

    std::string str;
    str.reserve(total_size_to_concat);
    
    for (std::size_t i = 0; i < s.length(); i++)
    {
      str.append(s[i], s[i].length());
    }
    

    But this is basically what your compiler do with operator+ and a minimum of optimization except it is guessing the size to reserve.
    Don't be shy. Take a look at the implementation of strings. :)

提交回复
热议问题