私はベクトルを含むクラス(foo)を持っています。C++:ベクトル "corrupting"の最初の要素
私はそうのようなベクトルの要素を反復処理しようとした場合:
for(vector<random>::iterator it = foo.getVector().begin();
it != foo.getVector().end(); ++it) {
cout << (*it) << endl;
}
最初の要素は常に破損していると、ゴミデータを返します。
行う場合は、何かのように:
vector<random> v = foo.getVector();
for(vector<random>::iterator it = v.begin();
it != v.end(); ++it) {
cout << (*it) << endl;
}
すべてが正常に動作しているように見えます。私が知らない「落ち穴」はありますか?
私はまた、Coutをやってみました。< < foo.getVector()[0] < < endl;ループの外側にあるが、それはうまく動作しているようだ。
ありがとうございました。
編集:
ここに私のヘッダファイルです:
#ifndef HITS
#define HITS
#include <vector>
#include "wrappers.h"
class Hits {
public:
Hits();
std::vector<word_idx_value> getVector() {return speech_hits;}
const std::vector<word_idx_value> getVector() const {return speech_hits;}
void add(const word_idx_value&);
Hits &operator+=(const Hits&);
private:
std::vector<word_idx_value> speech_hits;
};
#endif
getVector()メンバー関数が見えますか?多分何かそれを修正するでしょうか? – rlbond
getVector()は何を返しますか?それはベクターのコピーか、他の場所に保存されている既存のベクターへの参照ですか? – Wacek
私は値ではなく参照で返すように変更しました。それは正常に動作しているようですが、なぜ値渡しが結果に大きな影響を与えるのでしょうか? –