Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting an array of null terminated const char* strings to a std::vector< std::string >

I have a Visual Studio 2008 C++ function where I'm given an array of null-terminated strings const char* and a count of the number of strings in that array.

I'm looking for a clever way of turning an array of const char* in to a std::vector< std::string >

/// @param count - number of strings in the array
/// @param array - array of null-terminated strings
/// @return - a vector of stl strings
std::vector< std::string > Convert( int count, const char* array[] );

Boost is fine, STL is fine.

like image 808
PaulH Avatar asked Dec 16 '10 18:12

PaulH


2 Answers

Assuming that the signature of your function is inadvertently wrong, do you mean something like this?

#include <algorithm>
#include <iterator>
#include <string>
#include <vector>

std::vector<std::string> Convert(int count, const char **arr)
{
    std::vector<std::string> vec;
    vec.reserve(count);
    std::copy(arr, arr+count, std::back_inserter(vec));
    return vec;
}

int main()
{
    const char *arr[3] = {"Blah", "Wibble", "Shrug"};
    std::vector<std::string> vec = Convert(3, arr);
    return 0;
}
like image 64
Stuart Golodetz Avatar answered Sep 21 '22 04:09

Stuart Golodetz


Something like this?:

vector< string > ret( array, array + count );
like image 33
genpfault Avatar answered Sep 24 '22 04:09

genpfault