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

前端 未结 8 1017
南旧
南旧 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:42

    Google Abseil has function absl::StrJoin that does what you need.

    Example from their header file. Notice that separator can be also ""

    //   std::vector<std::string> v = {"foo", "bar", "baz"};
    //   std::string s = absl::StrJoin(v, "-");
    //   EXPECT_EQ("foo-bar-baz", s);
    
    0 讨论(0)
  • 2020-12-23 02:43

    You could use the std::accumulate() standard function from the <numeric> header (it works because an overload of operator + is defined for strings which returns the concatenation of its two arguments):

    #include <vector>
    #include <string>
    #include <numeric>
    #include <iostream>
    
    int main()
    {
        std::vector<std::string> v{"Hello, ", " Cruel ", "World!"};
        std::string s;
        s = accumulate(begin(v), end(v), s);
        std::cout << s; // Will print "Hello, Cruel World!"
    }
    

    Alternatively, you could use a more efficient, small for cycle:

    #include <vector>
    #include <string>
    #include <iostream>
    
    int main()
    {
        std::vector<std::string> v{"Hello, ", "Cruel ", "World!"};
        std::string result;
        for (auto const& s : v) { result += s; }
        std::cout << result; // Will print "Hello, Cruel World!"
    }
    
    0 讨论(0)
提交回复
热议问题