CocaCola
CocaCola

Reputation: 773

Why can't I delete an element in my vector?

I've got a fairly long program I'm working on and am having difficulty deleting an element from a vector. I've tried to do it with a very simple vector, and am having the same problem. As far as I can see, I've done it the same way everybody has explained in other people's questions. Here is the simple code.

vector<int> vect;
vect.push_back(3);
vect.push_back(2);
cout << vect[1];  // prints '2'
vect.erase(vect.begin()+1);
cout << vect[1] << endl; // prints '2'

What am I doing wrong?

It seems the above code works, because I checked the size at the end, and it printed '1'. The real code doesn't though:

size = A[i]->B().size();
cout << "size is " << A[i]->B().size() << endl;  // prints 21
A[i]->B().erase(A[i]->B().begin()+size);
cout << "size now " << A[i]->B().size() << endl;  // prints 21

I can't see what I've done differently? A is a vector, which stores other vectors. I want to delete the last element in the B vector.

Upvotes: 1

Views: 2153

Answers (3)

The Great Sauron
The Great Sauron

Reputation: 113

To delete the last elemnt in a vector, you can use .pop_back(). Also you should note that adding integers to an iterator is a bad idea. Use vector<int>::iterator instead as your variable to add.

Upvotes: 1

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133122

After you erase your element, your vector's size becomes 1 (because it was 2 before the erasing), essentially making your expression vect[1] result in undefined behavior, because there is no element with index 1 any more. All is left is a single element (value = 3, index = 0). If you used vect.at(1) instead of vect[1], it would throw std::out_of_range.

After your edit: Remember, if the size is N, then N is not a valid index for the vector!!! The elements are indexed 0, 1, 2, ... N-1. So indeed, the size is 1, therefore the only valid index is 0

Upvotes: 5

Matthieu M.
Matthieu M.

Reputation: 300439

What you are doing is undefined behavior. Basically, you are accessing past the currently last element of the vector, and you happen to find garbage that was left here. The problem is made evident using at instead of [] for accessing the element because at has built-in range checking.

// cout << vect[1] << endl;
cout << vect.at(1) << '\n';

If you replace [] by at as above, you will get a std::out_of_range exception signalling that the index you provided is invalid.

Upvotes: 2

Related Questions