Convert char ** (c) of unknown length to a vector <string> (C ++)
How would I go about converting C char ** to a C ++ vector? Is there some kind of built-in functionality that can be used for this, or is it better to execute it with a series of iterative steps?
EDIT: for various reasons, the number of elements in the C array is unknown. Perhaps I could pass this as another parameter, but is it absolutely necessary?
You can simply use the std::vector constructor, which 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 const char** :
const char** p = arr; std::vector<std::string> v(p, p + 4); which will also work with direct use of arr instead of p due to converting the array to a pointer.
You can use the std::vector constructor, which uses two iterators, like a range constructor :
char* strings[] = {"aaa", "bbb", "ccc", "ddd"}; std::vector<std::string> v(strings, strings + 4); where 4 is the size of your array. In this particular example, calculating the size of the strings array is also possible using the sizeof operator :
int len = sizeof(strings)/sizeof(char*); std::vector<std::string> v2(strings, strings + len); which would not be possible with pure char** , although since the size of the array cannot be directly extracted from the pointer in any way (itβs also worth reading something about the decomposable array ).