Pavan Dittakavi
Pavan Dittakavi

Reputation: 3181

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

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?

Upvotes: 8

Views: 2943

Answers (3)

Constantinius
Constantinius

Reputation: 35039

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());

Upvotes: 2

Evan Teran
Evan Teran

Reputation: 90422

well, depending on the performance requirements, you could just construct a 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
}

Upvotes: -1

James McNellis
James McNellis

Reputation: 354979

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.

Upvotes: 22

Related Questions