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?
With c++11 the stringstream way is not too scary:
Google Abseil has function absl::StrJoin that does what you need.
Example from their header file. Notice that separator can be also
""
C++03
C++11 (the MSVC 2010 subset)
C++11
Don't use
std::accumulate
for string concatenation, it is a classic Schlemiel the Painter's algorithm, even worse than the usual example usingstrcat
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.C++20
In the current draft of what is expected to become C++20, the definition of
std::accumulate
has been altered to usestd::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:My personal choice would be the range-based for loop, as in Oktalist's answer.
Boost also offers a nice solution:
This prints:
In any case, I find the
std::accumulate()
approach a misuse of that algorithm (regardless the complexity issues).A little late to the party, but I liked the fact that we can use initializer lists:
Then you can simply invoke (Python style):
Why not just use operator + to add them together?
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.