C++ 矢量从构造函数赋值对象,无需临时

c++ vector assign object from constructor without temporary

本文关键字:对象 赋值 构造函数 C++      更新时间:2023-10-16

我有一个类体素,它是用模板制作的,参数dim是空间维度(2D/3D(:

template<int dim>
class Voxel{
typedef Eigen::Matrix<float, dim, 1> vect;
private:
    vect Position; 
    vect Frequence; 
public:
    Voxel(vector<float>&, vector<float>& );
};
template<int dim>
Voxel<dim>::Voxel(vector<float> &coordinates, vector<float> &frequence){
    assert( ((dim==2) || (dim==3)) && "Spatial dimension at voxel   creation must be 2 or 3");
    for (int i; i<dim; ++i){
        Position[i] = coordinates[i]; 
        Frequence[i] = frequence[i];
     }
}

在另一个对象中:我有

template<int dim>
class Grid{
private:
    vector<float> size;
    vector<Voxel<dim>> voxels; ///< @brief List of the points. Maybe should be pointers ?
    unsigned int nb_voxels; ///< @brief total number of voxels in the grid
public:
    Grid(vector<float>&, vector<int>& );
};
template<int dim>
Grid<dim>::Grid(vector<float> &size, vector<int> &resolution)
    : size(size)
{
    nb_voxels = resolution[0];
    for (int d = 1; d < dim; ++d) {
        nb_voxels *= resolution[d];
    }
    voxels.resize(nb_voxels);
    vector<float> pos;
    pos.resize(dim);
    vector<float> freq;
    freq.resize(dim);
    vector<float> possible_coordinates;
    possible_coordinates.resize(nb_voxels);
    for (int d = 0; d < dim; ++d) {
        for (int k = 0; k < resolution[d] ; ++k) {
            possible_coordinates[k + d*resolution[d]] = k * size[d]/(resolution[d]-1); //ok
        }
    }
    for (int elem = 0; elem < nb_voxels; ++elem) {
        for (int d = 0; d < dim; ++d) {
            pos[d] = 0; //fixme
        }
        Voxel<dim> v(pos, freq);
        voxels[elem]= v;
    }
    cout << "nb points="<< nb_voxels <<endl;
}

最后是主要的:

int main (){
    vector<float> dimensions = {4, 8};
    vector<int> resolution = {2, 4}; ///< @brief must be >1 on each dim
        space_dim = dimensions.size();
    for (int d = 0; d < space_dim; ++d) {
        assert( (resolution[d]%2 == 0) && "resolution must be even");
    }
    if (space_dim == 2) {
        Grid<2> Grid(dimensions, resolution);
    }
    else if (space_dim == 3){
        Grid<3> Grid(dimensions, resolution);
    }
    return 0;
}

为什么我不能这样做?

voxels[elem] = Voxel<dim>(pos, freq);

也不是这个:

Voxel<dim> v (pos, freq);
voxels[elem] = v;

但我可以:没有调整矢量大小并执行以下操作:

    Voxel<dim> v(pos, freq);
    voxels.push_back(v);

我以为体素(pos,freq(会返回对象的实例并将其复制到元素中?

谢谢

您正在调用std::vector::resize它将调用值类型的默认构造函数,但Voxel中没有,因此会出现编译时错误。

使用 std::vector::reserve 分配内存,而不尝试默认构造。

体素[elem]

返回对位置 elem 处元素的引用(无效(,因为向量为空。您需要首先使用 std::vector::resize 将元素推送到向量,这将通过调用默认构造函数将元素推送到向量,以便使用 operator[] 。这应该有效:

vector<Voxel<dim>> voxels(nb_voxels);  //push nb_voxels to voxels vector

vector<Voxel<dim>> voxels;
voxels.resize(nb_voxels);

然后

voxels[elem] = Voxel<dim>(pos, freq);