2014-01-15 56 views
0

下面是一段代碼片段。 輸入到程序關於矢量值

dimension d[] = {{4, 6, 7}, {1, 2, 3}, {4, 5, 6}, {10, 12, 32}}; 
PVecDim vecdim(new VecDim()); 
    for (int i=0;i<sizeof(d)/sizeof(d[0]); ++i) { 
     vecdim->push_back(&d[i]); 
    } 
getModList(vecdim); 

計劃:

class dimension; 
typedef shared_ptr<vector<dimension*> > PVecDim; 
typedef vector<dimension*> VecDim; 
typedef vector<dimension*>::iterator VecDimIter; 

struct dimension { 
    int height, width, length; 
    dimension(int h, int w, int l) : height(h), width(w), length(l) { 

    } 
}; 

PVecDim getModList(PVecDim inList) { 
     PVecDim modList(new VecDim()); 
     VecDimIter it; 

     for(it = inList->begin(); it!=inList->end(); ++it) { 
      dimension rot1((*it)->length, (*it)->width, (*it)->height); 
      dimension rot2((*it)->width, (*it)->height, (*it)->length); 

      cout<<"rot1 "<<rot1.height<<" "<<rot1.length<<" "<<rot1.width<<endl; 
      cout<<"rot2 "<<rot2.height<<" "<<rot2.length<<" "<<rot2.width<<endl; 

      modList->push_back(*it); 
      modList->push_back(&rot1); 
      modList->push_back(&rot2); 
      for(int i=0;i < 3;++i) { 
       cout<<(*modList)[i]->height<<" "<<(*modList)[i]->length<<" "<<(*modList)[i]->width<<" "<<endl; 
      } 
     } 
      return modList; 
} 

我看到的是,價值ROT1和ROT2實際上覆蓋以前的值。 例如,cout語句按如下所示輸入頂部定義的輸入值。有人可以告訴我爲什麼這些值被覆蓋?

modList->push_back(&rot1); 

這些得到無效的每一個循環週期:

rot1 7 4 6 
rot2 6 7 4 
4 7 6 
7 4 6 
6 7 4 
rot1 3 1 2 
rot2 2 3 1 
4 7 6 
3 1 2 
2 3 1 

回答

3

,當你做這種事情你是存儲指向局部變量。首先不要存儲指針,這樣可以節省很多麻煩。

+0

但是向量會保存指針的副本,如果我沒有錯,每次都會是一個新的指針。它有什麼問題嗎? –

+2

@tariqzafar問題不在於指針,而在於指向何處。 – juanchopanza

+0

非常感謝:) –