I\'d like to build a std::string
from a std::vector
.
I could use std::stringsteam
, but imagine there is a s
Google Abseil has function absl::StrJoin that does what you need.
Example from their header file.
Notice that separator can be also ""
// std::vector<std::string> v = {"foo", "bar", "baz"};
// std::string s = absl::StrJoin(v, "-");
// EXPECT_EQ("foo-bar-baz", s);
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!"
}