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 s开发者_如何学Cound 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?
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.
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());
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
}
精彩评论