vector inside vector generates double values in the second dimension

Asked

Viewed 31 times

1

In the example below (which can also be seen in Ideone), I have a vector of a class and within the class I have an element too vector.

The point is that by doing the push_back class, the internal vector vetint should start from scratch each push_back of the first dimension, but c++ is keeping the previous values, hence the vector will duplicate.

#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;;
        }
    }
}

Produces that 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 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?

1 answer

2


The problem is because the method push_back() copies the element obj by executing a copy constructor.

An example of this builder would be:

// Construtor de cópia da classe
classe(classe const &c)
{
    var = c.var;
    vetint = c.vetint;
}

Therefore, the vector vetint is copied together with the elements that are already in it, causing the problem of value duplicity.

A possible solution is to create a new instance every iteration of looping inserting the object into the vector vetor:

#include <iostream>
#include <vector>

using namespace std;
class classe
{
public:
    int var;
    vector<int> vetint;
};

int main()
{
    vector<classe> vetor;

    for(unsigned i=0; i<2 ; i++) {
        classe obj; // AQUI: cria uma instância nova a cada iteração

        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;;
        }
    }
}

After execution, the output occurs as expected:

var(0) = 10
vetint(0) = 100
vetint(1) = 200
vetint(2) = 300
var(1) = 20
vetint(0) = 100
vetint(1) = 200
vetint(2) = 300

Browser other questions tagged

You are not signed in. Login or sign up in order to post.