2016-10-27 35 views
-2

我正在處理預先存在的代碼並檢查它是否工作。推回C++ std :: vector中的元素,他們失去了信息

用我最大的驚喜,這些基本類是給我麻煩現在

typedef int Id; 
typedef int BcId; 

//! This class gives some common methods to all mesh objects. 
class Identifier{ 
public: 

    static const UInt NVAL; 

    Identifier(UInt id):id_(id),bcId_(NVAL){} 
    Identifier(UInt id, UInt bcId):id_(id),bcId_(bcId){} 

    bool unassignedId()const {return id_==NVAL;} 
    bool unassignedBc()const {return bcId_==NVAL;} 

    Id id() const {return id_;} 
    BcId bcId() const {return bcId_;} 
    Id getId() const {return id_;} 


    protected: 
    Id id_; 
    BcId bcId_; 
}; 


//! This class implements a 3D point, the default is z=0 => 2D point 
class Point: public Identifier{ 
public: 

    static const UInt ndim = 3; 

    Point(): Identifier(NVAL, NVAL){coord_.resize(3);}; 
    Point(Real x, Real y, Real z=0):Identifier(NVAL, NVAL) 
     {coord_.resize(3);coord_[0]=x; coord_[1]=y; coord_[2]=x;} 
    Point(Id id, BcId bcId, Real x, Real y, Real z=0):Identifier(id, bcId) 
     {coord_.resize(3);coord_[0]=x; coord_[1]=y; coord_[2]=z;} 
    void print(std::ostream & out) const; 
    Real operator[](UInt i) const {return coord_[i];} 

    private: 
    std::vector<Real> coord_; 

}; 

void Point::print(std::ostream & out) const 
{ 
out<<"Point -"<< id_ <<"- "<<"("<<coord_[0]<<","<<coord_[1]<<","<<coord_[2]<<")"<<std::endl<<"------"<<std::endl; 
} 

用最簡單的測試:

int main() 
{ 
    Point a(1,1,0,0); 
    Point b(2,2,0,1); 
    Point c(3,3,1,0); 

    a.print(std::cout); 
    b.print(std::cout); 
    c.print(std::cout); 

    std::cout<<b.getId()<<std::endl; 
    b.print(std::cout); 

    std::vector<Point> points; 
    points.resize(3); 
    points.push_back(c); 
    points.push_back(b); 
    points.push_back(a); 


    std::cout<<"The points are"<<std::endl; 
    for (int i=0; i<3; ++i) 
     points[i].print(std::cout); 
    std::cout<<std::endl; 

} 

我得到的輸出:

Point -1- (0,0,0) 
------ 
Point -2- (0,1,0) 
------ 
Point -3- (1,0,0) 
------ 
2 
Point -2- (0,1,0) 
------ 
The points are 
Point -2147483647- (0,0,0) 
------ 
Point -2147483647- (0,0,0) 
------ 
Point -2147483647- (0,0,0) 
+0

你怎麼看待這個'points.resize(3);'? – Danh

+0

提示:'for(int i = 3; i <6; ++ i)' – George

+0

所以該死的愚蠢:) – user5609462

回答

3

這裏的問題是你用points.resize(3);而不是points.reserve(3);std::vector:::resize將更改爲所提供的大小的向量的大小。如果矢量增長,則插入必要的默認構造對象。在這種情況下,這意味着向量的前3個元素是默認構造的,並且您推入的3個點實際上位於索引的[3, 5]中。

如果您調用了std::vector::reserve,那麼它將爲3個對象分配空間,但不會創建任何默認實例。這意味着當你推回點將佔用指數的[0, 2]

相關問題