WilliamKF WilliamKF - 15 days ago 9
C++ Question

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

I'd like to build a

std::string
from a
std::vector<std::string>
.

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

std::string string_from_vector(const std::vector<std::string> &pieces) {
std::stringstream ss;

for(std::vector<std::string>::const_iterator itr = pieces.begin();
itr != pieces.end();
++itr) {
ss << *itr;
}

return ss.str();
}


How else might I do this?

Answer

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 << s; // Will print "Hello, Cruel World!"
}