Jump to content
  • Advertisement


This topic is now archived and is closed to further replies.


vector help?

This topic is 6066 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

im learning how to use vectors now, i know that you add values by using push_back(), and you can randomly access values, like
#include <vector>
#include <iostream>

int main()
    vector<int> myArray;

    int someNumber = myArray[1];
    cout << "value of myArray[1] is " << someNumber << endl;
but what im wondering is, can you delete myArray[1] in this vector? or am i going to have to learn how to use std::list too? Edited by - barazor on November 12, 2001 4:52:43 PM

Share this post

Link to post
Share on other sites
Yes, you _can_ delete myArray[ 1 ] (which would be the second element, or the middle element in this case.) You can use vector.erase on an iterator pointing to the second element. The question is, _should_ you? Not a whole lot.

Deleting or adding an element at any place but the end of the vector causes a performance hit. If you have 10000 elements, and you delete the first element, all 9999 elements have to be copied backward one place.

Vector is the STL container with the least amount of overhead, and therefore _potentially_ the "fastest" (if by speed you mean random access). However, it''s only efficient in particular situations. If you''re deleting or inserting in the middle elements a lot, you should probably be using a list instead.

Share this post

Link to post
Share on other sites
This is probably no use for you, but just in case: remember that if the ordering of the vector isn''t important, you can swap the values of the item you want to delete and the item at the end of the vector. Then you delete from the end, which is quicker than deleting from the middle. This might look something like:
std::swap(myArray[1], myArray[myArray.size()-1]);

Of course, this also relies on a swap being a fast operation, but there''s rarely any reason why a swap will cost more than 3 assignments, whereas shuffling a load of array elements along will nearly always involve much more than 3 assignments.

Share this post

Link to post
Share on other sites

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!