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

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

This may seem like a simple question, but I came across several websites that showed that such considerations could lead to a memory leak.

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

+8
c ++ vector stl
source share
3 answers

Well, depending on performance requirements, you can just build std::string as needed. Like this:

 for(std::vector<char*>::const_iterator it = v.begin(); it != v.end(); ++it) { std::string s = *it; // do something with s } 
0
source share

The conversion is pretty simple:

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

Once you have done this, you still need to make sure that the objects pointed to by pointers in ugly_vector are correctly destroyed. How you do this depends on the old code that you use.

+20
source share

Use std::copy :

 using namespace std; vector<char*> v_input; ... // fill v_input ... vector<string> v_output; v_output.resize(v_input.size()); copy(v_input.begin(), v_input.end(), v_output.begin()); 
+2
source share

All Articles