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?

+4
source share
4 answers

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.

+16
source
 char** c; vector<string> v(c, c + 10); 

Constructs elements from an element of a given range. 10 - the number of elements here

+8
source

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 ).

+1
source

This one line file is useful for capturing command line arguments ...

 int main(int argc, char ** argv) { std::vector<std::string> arguments(argv, argv + argc); } 
0
source

All Articles