C++ STL, deleting elements
If I have an STL vector, and I want to delete element at index i, is there a way to just say vector.delete(i)?
Thanks.
-Nick
Note that this is an O(n) operation. (If order does not matter, you could swap the element to be deleted with the last element; deleting the last element is O(1).)
To round this out a little:
If you erase an element or a few elements, all the elements following are shifted up. This means that the index you would have used to access them before is now not the same (and may even be invalid). So be warned...
If you are wanting to add or delete elements in the middle of a container then it may be more suitable for you to use a std::list. If you only want to add remove them from the end then std::deque may be the best choice.
If your container is storing objects rather than pointers to objects, erasing and inserting will be costly as the objects will have to be copied. If they are large objects then it could be very costly.
It may be more efficient to store pointers to objects. This makes it easier to insert and erase them as its simple pointers that are being shoved around rather than the objects themselves. This means though that you have to look after the allocation and deallocation of the actual objects pointed to. To make this easier, many people use smart pointers; in particular boost.shared_ptr.
If you erase an element or a few elements, all the elements following are shifted up. This means that the index you would have used to access them before is now not the same (and may even be invalid). So be warned...
If you are wanting to add or delete elements in the middle of a container then it may be more suitable for you to use a std::list. If you only want to add remove them from the end then std::deque may be the best choice.
If your container is storing objects rather than pointers to objects, erasing and inserting will be costly as the objects will have to be copied. If they are large objects then it could be very costly.
It may be more efficient to store pointers to objects. This makes it easier to insert and erase them as its simple pointers that are being shoved around rather than the objects themselves. This means though that you have to look after the allocation and deallocation of the actual objects pointed to. To make this easier, many people use smart pointers; in particular boost.shared_ptr.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement