Shortening Vectors

Is there a way to make a vector shorter once its length is defined? The book I'm reading says that iterators are needed, or at least that's how I understood it, but I don't quite understand iterators. Can someone give me an easy way to do this, and please explain it? Thanks in advance.
Last edited on
You can change the size with resize, and if that makes it smaller it will remove elements from the end of the vector.

Or you can erase individual items in the vector with erase.

Or you can remove individual items from the end of the vector with pop_back.

Or you can erase everything in the vector with clear
Last edited on
And if I want to remove something in the middle? How do I replace the removed element with the others? Should I post my code to show you what I mean?
Never mind, I got it. Thanks for the help! :)
vectors are not efficient for erasing or inserting elements in between,

better use "map" for that or a list.
I've been told that if one's vector doesn't contain that many elements, it can still be quite efficient when erasing or inserting elements in the middle. Maybe that is wrong though.
Last edited on
How well it performs depends on a lot of things. Like how efficiently the objects in the vector can be moved, the size of them, where in the vector you're removing from, the size of the vector, and maybe a half dozen other things.

Unless you have a relatively large vector and will be removing elements from the beginning/middle relatively frequently I wouldn't worry about it.
If the relative order of elements need not be maintained:

1
2
3
4
5
6
 // remove element at front
if( !seq.empty() )
{
    std::swap( seq.front(), seq.back() ) ;
    seq.pop_back() ;
}


1
2
3
4
5
6
 // remove element at position pos
if( seq.size() > pos )
{
    std::swap( seq[pos], seq.back() ) ;
    seq.pop_back() ;
}



Last edited on
Topic archived. No new replies allowed.