How to construct a std::string from a std::vector?

前端 未结 8 1016
南旧
南旧 2020-12-23 02:20

I\'d like to build a std::string from a std::vector.

I could use std::stringsteam, but imagine there is a s

相关标签:
8条回答
  • 2020-12-23 02:23

    A little late to the party, but I liked the fact that we can use initializer lists:

    std::string join(std::initializer_list<std::string> i)
    {
      std::vector<std::string> v(i);
      std::string res;
      for (const auto &s: v) res += s;
      return res;   
    }
    

    Then you can simply invoke (Python style):

    join({"Hello", "World", "1"})
    
    0 讨论(0)
  • 2020-12-23 02:24

    If requires no trailing spaces, use accumulate defined in <numeric> with custom join lambda.

    #include <iostream>
    #include <numeric>
    #include <vector>
    
    using namespace std;
    
    
    int main() {
        vector<string> v;
        string s;
    
        v.push_back(string("fee"));
        v.push_back(string("fi"));
        v.push_back(string("foe"));
        v.push_back(string("fum"));
    
        s = accumulate(begin(v), end(v), string(),
                       [](string lhs, const string &rhs) { return lhs.empty() ? rhs : lhs + ' ' + rhs; }
        );
        cout << s << endl;
        return 0;
    }
    

    Output:

    fee fi foe fum
    
    0 讨论(0)
  • 2020-12-23 02:28

    My personal choice would be the range-based for loop, as in Oktalist's answer.

    Boost also offers a nice solution:

    #include <boost/algorithm/string/join.hpp>
    #include <iostream>
    #include <vector>
    
    int main() {
    
        std::vector<std::string> v{"first", "second"};
    
        std::string joined = boost::algorithm::join(v, ", ");
    
        std::cout << joined << std::endl;
    }
    

    This prints:

    first, second

    0 讨论(0)
  • 2020-12-23 02:34

    Why not just use operator + to add them together?

    std::string string_from_vector(const std::vector<std::string> &pieces) {
       return std::accumulate(pieces.begin(), pieces.end(), std::string(""));
    }
    

    std::accumulate uses std::plus under the hood by default, and adding two strings is concatenation in C++, as the operator + is overloaded for std::string.

    0 讨论(0)
  • 2020-12-23 02:37

    With c++11 the stringstream way is not too scary:

    #include <vector>
    #include <string>
    #include <algorithm>
    #include <sstream>
    #include <iostream>
    
    int main()
    {
        std::vector<std::string> v{"Hello, ", " Cruel ", "World!"};
       std::stringstream s;
       std::for_each(begin(v), end(v), [&s](const std::string &elem) { s << elem; } );
       std::cout << s.str();
    }
    
    0 讨论(0)
  • 2020-12-23 02:41

    C++03

    std::string s;
    for (std::vector<std::string>::const_iterator i = v.begin(); i != v.end(); ++i)
        s += *i;
    return s;
    

    C++11 (the MSVC 2010 subset)

    std::string s;
    std::for_each(v.begin(), v.end(), [&](const std::string &piece){ s += piece; });
    return s;
    

    C++11

    std::string s;
    for (const auto &piece : v) s += piece;
    return s;
    

    Don't use std::accumulate for string concatenation, it is a classic Schlemiel the Painter's algorithm, even worse than the usual example using strcat in C. Without C++11 move semantics, it incurs two unnecessary copies of the accumulator for each element of the vector. Even with move semantics, it still incurs one unnecessary copy of the accumulator for each element.

    The three examples above are O(n).

    std::accumulate is O(n²) for strings.

    You could make std::accumulate O(n) for strings by supplying a custom functor:

    std::string s = std::accumulate(v.begin(), v.end(), std::string{},
        [](std::string &s, const std::string &piece) -> decltype(auto) { return s += piece; });
    

    Note that s must be a reference to non-const, the lambda return type must be a reference (hence decltype(auto)), and the body must use += not +.

    C++20

    In the current draft of what is expected to become C++20, the definition of std::accumulate has been altered to use std::move when appending to the accumulator, so from C++20 onwards, accumulate will be O(n) for strings, and can be used as a one-liner:

    std::string s = std::accumulate(v.begin(), v.end(), std::string{});
    
    0 讨论(0)
提交回复
热议问题