Reputation: 221
I've got a
std::vector<std::vector<char>>
and want to fill a std::vector<string>
with its content.
I just can't get my head into thinking how to access the inner vector of and put the chars into a string vector.
Maybe I'm wrong, but I think a std::vector<char>
is like a string.
So it should not be hard to do and I'm just stuck somewhere in my mind.
I've seen this: vector<string> or vector< vector<char> >? but it didn't got me far.
Thanks for your help.
Upvotes: 7
Views: 844
Reputation: 5731
This should work
std::vector<string> vec;
for(std::vector<std::vector<char>>::iterator itr = source.begin();
itr != source.end(); ++itr) {
vec.push_back(std::string(itr.begin(),itr.end()));
);
Upvotes: 3
Reputation: 18902
I think you can just do:
std::vector<char> v_char;
std::string my_string(v_char.begin(), v_char.end());
or also (requires C++11 and the vector of char must be NULL terminated):
std::string my_string(v_char.data());
Once you have the std::string
, filling a vector is easy.
Upvotes: 2
Reputation: 20990
Here's an algorithm
version
std::vector<std::vector<char>> a;
std::vector<std::string> b;
std::transform(a.begin(), a.end(), std::back_inserter(b),
[](std::vector<char> const& v) -> std::string {
return {v.begin(), v.end()};
});
Upvotes: 13
Reputation: 476930
The naive solution should work well enough:
std::vector<std::string>
chars_to_string(std::vector<std::vector<char>> const & in)
{
std::vector<std::string> out;
out.reserve(in.size());
for (auto const & v : in)
out.emplace_back(v.begin(), v.end());
return out;
}
Upvotes: 11