c ++ vector从构造函数中分配对象而不是临时的

时间:2015-03-30 09:04:04

标签: c++ templates vector

我有一个类体素,它是用模板制作的,参数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);

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

感谢

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

  

体素[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);