Memory reserve with std :: vector resize

2

for a data structure std::vector<3Dpoint> v; with 3Dpoint :

struct 3Dpoint { 
    float x, y, z; 
    3Dpoint(float _x, float _y, float _z){
        x = _x;
        y = _y;
        z = _z;
}};

I try to resize the vector size v , using v.resize(m*n); . My intention is to reserve m*n structures 3Dpoint . In doing so, I get the error: no matching function for call to ‘Punto3D::Punto3D()’ . How could I resize this vector? Thanks

    
asked by Pablo Donoso 11.10.2017 в 17:58
source

1 answer

2

resize( ) needs a default constructor. If the size you request is greater than the current size of the vector, this will insert elements by default , by calling that constructor.

If you want to ensure that you have space for m * n elements, without inserting (that is, making the vector reserve memory for them ), the right thing to do is

vector.reserve( m * n );

Doing so, you ensure that the vector will not call the allocator more than 1 time , so you get all the necessary memory hit >, without inserting nothing in the vector .

If you want, however, to add m * n elements already built , you only have to modify the constructor of your class:

struct 3Dpoint { 
    float x, y, z; 
    3Dpoint( float _x = 0.0f, float _y = 0.0f, float _z = 0.0f ) {
        x = _x;
        y = _y;
        z = _z;
} };

Or, if you find it more comfortable, you can let the compiler do it for you:

struct 3Dpoint { 
    float x, y, z; 
    3Dpoint( ) = default;
    3Dpoint( float _x, float _y, float _z ) {
        x = _x;
        y = _y;
        z = _z;
} };

The result is the same: the variables x, y, z remain at 0.0f .

    
answered by 11.10.2017 в 18:11