In the example below (which can also be seen in the Ideone ), I have vector
of a class and within class I I have an element also vector
.
The point is that when doing push_back
of the class, the internal vector vetint
should start from zero every% of% of the first dimension, but c ++ is holding the previous values, hence the vector doubles.
#include <iostream>
#include <vector>
using namespace std;
class classe
{
public:
int var;
vector<int> vetint;
};
int main()
{
vector<classe> vetor;
classe obj;
for (unsigned i=0; i<2 ; i++) {
obj.var = (i+1)*10;
for (unsigned c=0; c<3 ; c++) {
obj.vetint.push_back((c+1)*100);
}
vetor.push_back(obj);
}
for (unsigned i=0; i < vetor.size() ; i++) {
cout << "var(" << i << ") = " << vetor[i].var << endl;
for (unsigned c=0; c < vetor[i].vetint.size() ; c++) {
cout << "vetint(" << c << ") = " << vetor[i].vetint[c] << endl;;
}
}
}
Produce this result:
var(0) = 10
vetint(0) = 100
vetint(1) = 200
vetint(2) = 300
var(1) = 20
vetint(0) = 100
vetint(1) = 200
vetint(2) = 300
vetint(3) = 100
vetint(4) = 200
vetint(5) = 300
When the desired one would be:
var(0) = 10
vetint(0) = 100
vetint(1) = 200
vetint(2) = 300
var(1) = 20
vetint(0) = 100
vetint(1) = 200
vetint(2) = 300
Why does this happen? How to solve?