2011-07-02 1 views
3

にベクターにヒープに割り当てられた文字を一backとき:あなたは、私は次の操作を実行したとき、私は*></p> <p>ベクトル<のcharにchar *型を挿入し、トラブルを抱えているC++

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++) 
    cout << *it << endl; 

私が得ました出力:

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

World 
d 

誰もが何が起こっているのを私に言うだろうし、私はこの問題を解決できる方法 .. *それは間違ったことを指しているように私には思えますか?

答えて

3

をあなたのコードで間違っていますか?

その他の答えは、より良い方法でそれを行う方法を説明します。私の答えは、あなたのコードが期待通りに動作しない理由と、それを動作させるための迅速な修正を説明しています。 Withステートメント

:あなたはベクトルにしてオブジェクトをプッシュした後、あなたは、文字列を削除

delete[] cstr; 

が、これはあなたのベクトル要素がすでに割り当て解除された何かを指すようになります。

この行をコメントアウトしてもう一度確認すれば正常に動作します。

ここにはIdeoneのコードのworking sampleがあります。

この場合、あなたのベクトルは、動的に割り当てられたメモリ空間を指し示す含まれたオブジェクトポインタを削除することの所有権を取る必要があります。

はそれを行う方法についてthisを参照してください。 STLのイテレータについては

+0

+1を質問に答えると、遠回しに言うのではないため – Nick

4

なぜvector<std::string>を使用しないのですか?それは次のようになります。

#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; 
} 
0

は、次の構文を使用します。

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

(++、それはアルゴリズムの性能を向上さに気づく)

関連する問題