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.
Thanks,
PaulH
Something like this?:
vector< string > ret( array, array + count );
Try this:
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>
#include <iostream>
int main(int argc,char* argv[])
{
// Put it into a vector
std::vector<std::string> data(argv, argv + argc);
// Print the vector to std::cout
std::copy(data.begin(), data.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
}
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;
}
I assume in your array strings are separated by 0s.
std::vector< std::string > Convert( int count, const char* array )
{
std::vector< std::string > result;
for(const char* begin = array; count; --count)
{
const char* end = begin;
for(; *end; ++end);
result.push_back(std::string(begin, end));
begin = end + 1;
}
return result;
}