Convert char** (c) of unknown length to vector<string> (c++)

MirroredFate picture MirroredFate · Mar 29, 2013 · Viewed 9.3k times · Source

How would one go about converting a C char** to a C++ vector? Is there some built-in functionality one can utilize to do this, or is it better to accomplish it through a series of iterative steps?

EDIT: For various reasons, the number of elements in the C array is unknown. It is possible I could pass that as another parameter, but is that absolutely necessary?

Answer

Joseph Mansfield picture Joseph Mansfield · Mar 29, 2013

You can simply use the constructor of std::vector that takes two iterators:

const char* arr[] = {"Hello", "Friend", "Monkey", "Face"};
std::vector<std::string> v(std::begin(arr), std::end(arr));

Or if you really have a const char**:

const char** p = arr;
std::vector<std::string> v(p, p + 4);

Which will also work with directly using arr instead of p due to array-to-pointer conversion.