How do I convert a vector<string> to a const char* const* in c++?

  • A+
Category:Languages

I am trying to convert data into the right format for a specific unit test. The task is to mine a set of words, the unit tests will make sure the results are correct. I have no access to the unit tests, just the declaration which takes a const char* const* Result.

So I need to get my

std::vector<string> Words;  

to

const char* const* Result; 

divided by a non-alpha char (for example space).

I am aware that this is a constant pointer to a constant character, so I am not sure what to do here since they both constant?

Any pointers (word pun not really intended) are appreciated!

 


You cannot meaningfully convert one to the other. However, you can convert an array of std::string into an array of pointers to char, and a pointer to the first element of such array would be compatible with your desired result:

std::vector<const char*> Ptrs; std::transform(     std::cbegin(Words), std::cend(Words),     std::back_inserter(Ptrs),     [](auto& str)  { return str.c_str(); } ); const char* const* Result = Ptrs.data(); 

Just remember that those pointers within the new vector are only valid as long as the strings in the original vector exist, aren't resized, and the original vector itself isn't resized. And the pointer to first element of the new vector is only valid as long as that vector exists and isn't resized.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: