Archived

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

vector help?

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 #include int main() { vector myArray; myArray.push_back(3); myArray.push_back(5); myArray.push_back(32); 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 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 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]);myArray.pop_back();

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 on other sites
thanks alot, that is exactly the kind of thing i was looking for :D

• Forum Statistics

• Total Topics
628329
• Total Posts
2982104

• 22
• 9
• 9
• 13
• 11