2d Vector with wrong values

I'm studing STL, then i thought "i'll make a 2d array!" but whatever...

a coded this:

vector< vector<int> > vetor;

vetor.resize(10);
vetor[0].resize(10);

for(int i = 0; i < vetor.capacity(); i++){
    for(int h = 0; h < vetor[0].capacity();h++){
        vetor[i][h] = h;
    }

}

Until here, ok. But when i try to show the array value a use this:

for(int i = 0; i < vetor.capacity(); i++){
    cout << "LINE " << i << ": ";
    for(int h = 0; h < vetor[0].capacity();h++){
        cout << vetor[i][h] <<" ";
    }
    cout << "\n";
}

And the results are really wrong:

LINE 0: 4 5 6 7 8 9 6 7 8 9
LINE 1: 0 1 2 3 0 1 2 3 0 1
LINE 2: 0 1 2 3 0 1 2 3 0 1
LINE 3: 0 1 2 3 0 1 2 3 0 1
LINE 4: 0 1 2 3 0 1 2 3 0 1
LINE 5: 0 1 2 3 0 1 2 3 0 1
LINE 6: 0 1 2 3 0 1 2 3 0 1
LINE 7: 0 1 2 3 0 1 2 3 0 1
LINE 8: 0 1 2 3 0 1 2 3 4 5
LINE 9: 0 1 2 3 4 5 6 7 8 9

What's happening with my program? it isn't printing the right values!

Upvotes: 0

Views: 283

Answers (1)

Andrew Tomazos
Andrew Tomazos

Reputation: 68698

Several issues:

You are only resizing the first vector. You need to resize all of them.

Instead consider using this:

vector< vector<int> > vetor (10, vector<int>(10, 0));

this will create a 10 x 10 vector of vectors.

vector has a constructor (size_t size, T default_value) which constructs the vector with size elements of value default_value.

If the size of the vector is known at compiletime and is not going to change you can also use a std::array instead for a slight performance gain.

Secondly use vector::size() not vector::capacity() to determine the size of a vector (capacity refers to the backing store, and can be largely ignored except for optimization)

for(int i = 0; i < vetor.size(); i++){
    for(int h = 0; h < vetor[0].size(); h++){
        vetor[i][h] = h;
    }
}

When you resize vetor[0].resize(10) you are only resizing the first element.

You would need to:

vetor[0].resize(10)
vetor[1].resize(10)
vetor[2].resize(10)
.
.
vetor[10].resize(10)

to do what you want to do.

(Put another way each vector in the vector of vectors has a potentially different size. It is not a matrix class.)

Upvotes: 3

Related Questions