创建 class 的多个实例并将它们存储在 vector<class> 中

Create multiple instances of class & store them in vector<class>

我想做的是创建 class Point 的多个实例并访问每个实例的 class 变量。

class Point
{
public:
    float x, y, z;
};

在下面的 main() 程序中,我创建了一个名为 point_ 的类型 Point 的实例,并在向量中多次推送同一个实例。

int main() 
{

    std::vector < Point > vect;
    Point point_;

    int num_instances; // is user defined

    for (int i = 0; i < num_instances; i++)
    {
        vect.push_back(point_); // (^^^)
    }
}

(^^^) 此处,问题 是此 Point 类型的向量添加了我手动创建的 1 个单个实例(称为 point_)。 我想要的是基于num_instances来自用户的输入(比如说5),应该创建相同数量(即5)的Point类型的实例并且存储在此向量中(称为 vect)。

In the following main() program, I'm creating a single instance of type Point, called point_ and pushing the same instance multiple times in the vector.

是的,您正在创建名为 point_ 的类型 Point 的单个实例。不,您没有在向量中多次推送同一个实例。

如果您将同一个实例多次推入向量中,则意味着该实例同时位于多个位置。这不可能发生。我将使用物理纸质文档进行类比。如果您想多次将此文档放入一堆文档中,则必须复制它。您的 Point 对象也是如此。

当您在向量上调用 push_back 时,它会为 Point 分配内存并将给定的 Point 对象复制到该内存中。由于它将为向量中的每个项目分配完全独立的内存块,因此它们不可能是同一个对象。

编辑: 证明如下:http://ideone.com/F5XX4u

而不是使用 push_back,它执行以下操作:

Appends the given element value to the end of the container.

1) The new element is initialized as a copy of value.

2) value is moved into the new element.

您可以使用 emplace_back,它根据参数构造一个全新的对象并将其附加到矢量。

你可以这样使用它:

int main() 
{

    std::vector < Point > vect;

    int num_instances; // is user defined

    for (int i = 0; i < num_instances; i++)
    {
        // You should use the values you want here
        float x = 0.0f;
        float y = 0.0f;
        float z = 0.0f;
        vect.emplace_back(x, y, z);
    }
}

push_back 方法复制了你推入的项目。为了证明这一点,当你 运行 下面的代码

#include "stdio.h"
#include "stdlib.h"
#include "math.h"
#include <vector>

class Point
{
    public:
    float x, y, z;
};

int main()
{

    std::vector < Point > vect;
    Point point_;
    int num_instances = 5; // is user defined

    for (int i = 0; i < num_instances; i++)
    {
        vect.push_back(point_); // (^^^)
    }

    for (int i = 0; i < num_instances; i++){
      printf(" %d: %x\n", i, &(vect[i]) );
    }
}

您得到以下输出:

0: fbd00060
1: fbd0006c
2: fbd00078
3: fbd00084
4: fbd00090

这意味着向量中的每个对象都是不同点对象的实例。如果它们是同一个实例,那么它们都会有相同的地址