ベクトルを含むクラス(foo)があります。
次のように、ベクトル内の要素を反復処理しようとすると、次のようになります。
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