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

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

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

    #include 
    #include 
    #include 
    #include 
    
    int main()
    {
        std::vector 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 
    #include 
    #include 
    
    int main()
    {
        std::vector v{"Hello, ", "Cruel ", "World!"};
        std::string result;
        for (auto const& s : v) { result += s; }
        std::cout << result; // Will print "Hello, Cruel World!"
    }
    

提交回复
热议问题