I\'d like to build a std::string
from a std::vector
.
I could use std::stringsteam
, but imagine there is a s
You could use the std::accumulate() standard function from the
header (it works because an overload of operator +
is defined for string
s 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!"
}