Domainというクラスがあり、そのメンバーには。という保護されたメンバーstd::vector
が
ありitsVec
ます。ベクトルには、を介してアクセスできますgetVec()
。
でmain()
要素を直接アドレス指定すると、正常に機能します
getVec()[i]
。ただし、イテレータを使用しようとすると、最初の要素へのポインタが正しく初期化されていないようです。奇妙なことに、クラスコンストラクターでイテレーターを使用するitsVec
と、チャームのように機能します。
コード
#include<iostream>
#include <vector>
class Domain
{
public:
/* ==================== LIFECYCLE ======================================= */
Domain ( ) {}; /* constructor */
Domain ( unsigned int , const unsigned int * ) ; /* custom constructor */
Domain ( const Domain &other ); /* copy constructor */
~Domain ( ) {}; /* destructor */
/* ==================== ACCESSORS ======================================= */
unsigned int getDim() const {return itsDim;}
std::vector<unsigned int> getVec() const {return itsVec;}
protected:
/* ==================== DATA MEMBERS ======================================= */
unsigned int itsDim;
std::vector<unsigned int> itsVec;
}; /* ----- end of class Domain ----- */
Domain::Domain( unsigned int dim, const unsigned int *externVec)
{
itsDim = dim;
for ( size_t j = 0; j < dim ; j++ )
itsVec.push_back(externVec[j]);
std::vector<unsigned int>::const_iterator i_vec = itsVec.begin();
// iterator access works
for ( ; i_vec != itsVec.end(); i_vec++)
std::cout<<"Iterator in constructor: " << (*i_vec) << std::endl;
std::cout<<std::endl;
} /* ----- end of constructor ----- */
/*-----------------------------------------------------------------------------
* Main
*-----------------------------------------------------------------------------*/
int main ()
{
const unsigned int kVec[3] = { 1, 2, 3 };
Domain k(3,kVec);
size_t i = 0;
// direct access works
for( ; i<3 ; i++)
std::cout << "Vec direct: " << k.getVec()[i] << std::endl;
std::cout << std::endl;
// iterator access FAILS for the first element
std::vector<unsigned int>::const_iterator it_vec = k.getVec().begin();
for ( ; it_vec != k.getVec().end(); it_vec++)
std::cout<<"Vec iterator " << (*it_vec) << std::endl;
return 0;
} /* ---------- end of function main ---------- */
g++ main.cc -o test
結果とコンパイル
$ ./test
Iterator in constructor: 1
Iterator in constructor: 2
Iterator in constructor: 3
Vec direct: 1
Vec direct: 2
Vec direct: 3
Vec iterator 140124160
Vec iterator 2
Vec iterator 3
別のマシンでテストすると、次のようになりました。
Vec iterator 0
Vec iterator 0
Vec iterator 3
私がgetVec()
間違ってベクトルを返す方法です。イテレータは正しく処理されていませんか?私には手がかりがなく、ここで何が間違っているのか、それを修正する方法がありません。
どんな助けでも大歓迎です、
ダフレンク