How to construct a std::string from a std::vector<string>?
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 (hencedecltype(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{});
You could use the std::accumulate()
standard function from the <numeric>
header (it works because an overload of operator +
is defined for string
s 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!"
}
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