Object vector from custom class

In C ++, I declare a custom class to store some values ​​for an object. Then I declare the vector of the specified object. Finally, I iterate over the vector to assign values ​​to the fields.

#include <vector>

using namespace std;

class Custom
{ 
    public:
        int metric,nX,nY;
    private:

};

int main( int argc, char** argv )
{

vector<Custom> MyWonderfulVector;

// Some code//

for(int i=0 ; i<10 ; i++){

MyWonderfulVector[i].metric = computation1();
MyWonderfulVector[i].nX= computation2();
MyWonderfulVector[i].nY= computation3();
}

return 0;

}

He throws out vector subscript out of rangewhen trying to evaluate MyWonderfulVector[i].metric = computation1();. metricis an int, computation1()too. in the first iteration, i = 0, so this should be fine. It is curious that in another place in the code I have a vector of another class (included in the library), and this syntax works for it, so I don’t understand why it does not work here.

EDIT:

Good with the comments that I changed to the following line: vector MyWonderfulVector (10);

, , ( Matlab;)). , , , _ "" . , , push_back temp . ...

+4
5

vector<Custom> MyWonderfulVector;

- empty

std::cout << std::boolalpha << MyWonderfulVector.empty() << std::endl;

true

, , ampty, 0, .

some_variable,

vector<Custom> MyWonderfulVector( some_variable );

. some_variable - push_back .

vector<Custom> MyWonderfulVector;
MyWonderfulVector.reserve( some_variable );


for ( int i=0 ; i<some_variable ; i++ )
{
    Custom obj;
    obj.metric = computation1();
    obj.nX= computation2();
    obj.nY= computation3();

    MyWonderfulVector.push_back( obj );
}
+7

vector Custom

   vector<Custom> MyWonderfulVector;

vector. . vector for, vector, .

.

  • vector .

     vector<Custom> MyWonderfulVector(10);
    
  • vector for.

    for(int i=0 ; i<10 ; i++){
      Custom c;
      c.metric = computation1();
      c.nX= computation2();
      c.nY= computation3();
      MyWonderfulVector.push_back(c);
    

    }

+7

. push_back vector, . , .

+2
+1

resize() , . , :

for(int i=0 ; i<10 ; i++){

MyWonderfulVector.resize(i);

MyWonderfulVector[i].metric = computation1();
MyWonderfulVector[i].nX= computation2();
MyWonderfulVector[i].nY= computation3();
}

, size_t , .

size_t my_vector_size = MyWonderfulVector.size();
for(int i=0 ; i<10 ; i++)
{
    my_vector_size++;
    MyWonderfulVector.resize(my_vector_size);
}

.

0

All Articles