8

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?

James McNellis
  • 348,265
  • 75
  • 913
  • 977
Pavan Dittakavi
  • 3,013
  • 5
  • 27
  • 47
  • 1
    There's nothing inherently leaky about using vectors, except that they're relatively more memory-expensive while alive. Just use the regular vector operations and destruct it when you're done. char* can easily be converted to a proper c++ string using the string library. – Rag Aug 01 '11 at 15:36

3 Answers3

22

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.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
2

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());
James McNellis
  • 348,265
  • 75
  • 913
  • 977
Constantinius
  • 34,183
  • 8
  • 77
  • 85
-1

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
}
Evan Teran
  • 87,561
  • 32
  • 179
  • 238