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

扶醉桌前 提交于 2019-12-12 09:39:53

问题


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?


回答1:


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.




回答2:


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

Will construct elements from element of given range. 10 is number of elements here




回答3:


You can use the constructor of std::vector that takes two iterators, a.k.a. the 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 concrete example, the calculation of the size of the strings array would be also possible by using sizeof operator:

int len = sizeof(strings)/sizeof(char*);
std::vector<std::string> v2(strings, strings + len);

which wouldn't be possible with pure char** though since the size of the array can not be directly retrieved from a pointer in any way (also worth to read something about array decaying).




回答4:


This one-liner is useful for capturing command line arguments...

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


来源:https://stackoverflow.com/questions/15709585/convert-char-c-of-unknown-length-to-vectorstring-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!