Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a vector<vector<char>> into a vector<string>

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.

like image 881
jan Avatar asked Apr 04 '14 09:04

jan


People also ask

How do you make a vector into a string?

You can create a string using double quotes. As an alternative, you can convert a character vector to a string using the string function. chr is a 1-by-17 character vector. str is a 1-by-1 string that has the same text as the character vector.

How do you return a vector string in C++?

A function can return a vector by its normal name. A function can return a vector literal (initializer_list), to be received by a normal vector (name). A vector can return a vector reference, to be received by a vector pointer. A vector can return a vector pointer, still to be received by another vector pointer.


2 Answers

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()};
});
like image 101
user657267 Avatar answered Nov 15 '22 22:11

user657267


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;
}
like image 21
Kerrek SB Avatar answered Nov 16 '22 00:11

Kerrek SB