回推c++ std::vector中的元素,它们会丢失信息
Pushing back elements in c++ std::vector, they lose information
我正在处理一个预先存在的代码,并检查它是否有效。
最令我惊讶的是,这些基础类给我带来了麻烦
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)
这里的问题是您使用points.resize(3);
而不是points.reserve(3);
。std::vector:::resize
将把向量的大小更改为所提供的大小。如果vector增长,则插入必要的默认构造对象。在这种情况下,这意味着vector的前3个元素是默认构造的,而您放入其中的3个点实际上位于index的[3, 5]
中。
如果您调用了std::vector::reserve
,那么它将为3个对象分配空间,但不会创建任何默认实例。这意味着当你把这些点往后推时,它们会占用索引的[0, 2]
vector::resize不是正确的函数,它实际上是调整数组的大小,然后push_back添加另一个三个元素。
你可能想用vector::reserve
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 正在查找文档以获得PS4平台的C++中的设备信息
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用strcpy将char数组的元素复制到另一个数组
- 使用不带参数的函数访问结构元素
- 给定n个元素的m个集合.在C++中找到出现在最大集合数中的元素
- C++如何通过用户输入删除列表元素
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- lower_bound()返回最后一个元素
- 基于多个条件处理地图中的所有元素
- 调整大小后指向元素值的指针unordered_map有效?
- 如何在函数模板中隐式推导数组中元素的类型信息
- 数组的指针,该数组的每个元素的内存空间信息存储在哪里
- 是否可以根据另一个向量的信息从一个向量中删除某些元素
- 需要帮助将数组元素/信息传递给函数C++
- 我在尝试访问矢量<string>元素时收到错误,文本中的信息
- 在位置 i 处插入元素,并根据 i 第一个元素返回信息
- 回推c++ std::vector中的元素,它们会丢失信息
- 在未排序数组中查找第二小元素的详细信息
- 存储其他信息以及 cv::Mat 元素