开发者

when you push_back heap-allocated char into a vector in c++

I'm having trouble inserting char* into a vector< char*>

When I do the following:

string str = "Hello b World d"
char *cstr, *p;
vector<char*> redn;
cstr = new char [ (str.size)+1 ];
strcpy(cstr, str.c_str());

//here I tokenize "Hello b World d"
p = strtok(cstr," ");  
while(p!=NULL){
    redn.push_back(p);
    cout << "just pushed back: " << redn.back() << endl;
    p = strtok(NULL," ");
}
delete[] cstr;

//now check

for(it= redn.begin(); it < redn.end(); it++)
  开发者_StackOverflow   cout << *it << endl;

I got an output of:

just pushed back: Hello
just pushed back: b
just pushed back: World
just pushed back: d
p0s

World
d

It seems to me that *it is pointing to the wrong thing.. Would anybody tell me what's going on and how I could fix this?


Why don't you just use vector<std::string>? It would look like this then:

#include <string>
#include <sstream>
#include <iterator>
#include <vector>
#include <iostream>

int main() {
    std::string s = "Hello b World d";
    std::stringstream stream(s);
    std::vector<std::string> tokens(
        (std::istream_iterator<std::string>(stream)),
        (std::istream_iterator<std::string>()));
    for(std::vector<std::string>::iterator it = tokens.begin();
        it != tokens.end(); ++it)
        std::cout << *it << std::endl;
}


What is wrong in your code?

Other answers explain you how to do it in a better way. My answer explains why your code doesn't work as you expected it to and a quick fix to get it working.

With the statement:

delete[] cstr;

You delete the string after you push the object in to the vector, this causes your vector elements to point to something that has already been de-allocated.

comment out that line and check again, it will work.

Here is the working sample of your code on Ideone.

Your vector in this case needs to take the ownership of deleting each of the contained object pointer which points to a dynamically allocated memory space.

See this for how to do that.


For STL iterators use the following syntax:

vector<char*>::iterator it;
for(it= redn.begin(); 
    it != redn.end(); 
    ++it)
{
   cout << *it << endl;
}

(notice the ++it boost the algorithm performance)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜