7

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.

Community
  • 1
  • 1
jan
  • 211
  • 1
  • 7

4 Answers4

13

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()};
});
user657267
  • 20,568
  • 5
  • 58
  • 77
11

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;
}
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
3

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()));
);
Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
Mantosh Kumar
  • 5,659
  • 3
  • 24
  • 48
  • Since you are using C++11, I would advise: `for (auto const& e: source)` it's so much more readable. Also note that repeatedly computing `source.end()` at each iteration of the loop is not particularly "nice". – Matthieu M. Apr 04 '14 at 11:09
2

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.

manlio
  • 18,345
  • 14
  • 76
  • 126
  • The first is definitely the way to go; it's also extremely efficient since the `std::string` can compute the expected length in O(1) as the difference between the two iterators and thus pre-reserve memory once and for all. – Matthieu M. Apr 04 '14 at 11:11