I have a std::vector<std::string> that I need to use for a C function’s argument that reads char* foo. I have seen how to convert a std::string to char*. As a newcomer to C++, I’m trying to piece together how to perform this conversion on each element of the vector and produce the char* array.
I’ve seen several closely related SO questions, but most appear to illustrate ways to go the other direction and create std::vector<std::string>.
You can use
std::transformas:Which requires you to implement
convert()as:Test code:
Output:
Online demo : http://ideone.com/U6QZ5
You can use
&vc[0]wherever you needchar**.Note that since we’re using
newto allocate memory for eachstd::string(inconvertfunction), we’ve to deallocate the memory at the end. This gives you flexibility to change the vectorvs; you canpush_backmore strings to it, delete the existing one fromvs, andvc(i.evector<char*>will still be valid!But if you don’t want this flexibility, then you can use this
convertfunction:And you’ve to change
std::vector<char*>tostd::vector<const char*>.Now after the transformation, if you change
vsby inserting new strings, or by deleting the old ones from it, then all thechar*invcmight become invalid. That is one important point. Another important point is that, you don’t need to usedelete vc[i]in your code anymore.