Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a vector<char*> to a vector<string>/string

Tags:

c++

stl

vector

We have a legacy method that returns a vector of char pointers i.e., vector<char *>. Now, I need to process only strings (std::string). How can I do this?

This question may sound simple, but I run into couple of websites which depicted that these sort of considerations might lead to memory leaks.

Now, I either want to get a vector<string> or even a string without any memory leaks. How can I do this?

like image 692
Pavan Dittakavi Avatar asked Aug 01 '11 15:08

Pavan Dittakavi


1 Answers

The conversion is quite straightforward:

std::vector<char*> ugly_vector = get_ugly_vector();
std::vector<std::string> nice_vector(ugly_vector.begin(), ugly_vector.end());

Once you've done that, though, you still need to make sure that the objects pointed to by the pointers in ugly_vector are correctly destroyed. How you do that depends on the legacy code you are utilizing.

like image 113
James McNellis Avatar answered Sep 28 '22 13:09

James McNellis