It seems that with vectors you can only delete via iterators. Since I can access and update by index [], shouldn't I be able to delete by index?

The reason I ask is that when you delete via the iterators and the value exists multiple times, I believe it deletes all instances. I just want to delete a specific one.

If you want to delete only one offset, use only one iterator.

vector<int> v;
for (i = 0; i < 10; ++i) {
    v.push_back(i);
}

v.erase(v.begin() + 7);

for (i = 0; i < v.size(); ++i) {
    cout << v[i] << endl;
}

Output:

0
1
2
3
4
5
6
8
9

See cppreference.com if you want more info on how erase() works.

Comments
Haven't I given you rep yet? You've surely earned more than this.

RF,

Worked like a charm. Thanks for your help. (By the way, I'm assuming this is a somewhat expensive operation if I have a lot of items in the vector and I erase one of the ones at the top? )

RF,

Worked like a charm. Thanks for your help. (By the way, I'm assuming this is a somewhat expensive operation if I have a lot of items in the vector and I erase one of the ones at the top? )

Yes, deleting members is very inefficient operation on vector, for much better performance use lists if you need to delete elements often...

Any drawbacks to using a list over a vector? (I don't have a particular requirement to use a vector, it's just what I was using before...)

Any drawbacks to using a list over a vector? (I don't have a particular requirement to use a vector, it's just what I was using before...)

Well, you can think of vector just like an array (dynamic array). And you know that arrays enable random access u.e. you can acces elements very quickly through corresponding index. Appending and removing elements from the end is very fast. However, inserting an element in the middle or at the beginning of the array takes time because all the following elements have to be moved to make room for it while maintaining the order.
On the other hand, a list is implemented as a doubly linked list of elements, but it doesn't provide random access, example, to access the tenth element, you must navigate the first nine elements by following the chain of their links. that is in geral drawback of a list comparing with vector.
The advantage of a list is that the insertion or removal of an element is fast at any position. Only the links must be changed


Hope this helps

- Micko

OK Thanks. I do a hell of a lot more adding (via push_back at the end) than deleting, so I think I'll stick with the vector.

push_back and pop_back are both constant time, efficient operations anyway. The only time I find lists useful is when I have a bunch of iterators sitting around, pointing at specific nodes of the list.

This article has been dead for over six months. Start a new discussion instead.