Jump to content
  • Advertisement
Sign in to follow this  
Toonkides

STL Vector class : deleting elements of,

This topic is 4949 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

I know you can do : pop_back() OR erase(iterator), but how would i delete a specific nth element ? My guess is simply : vector<int>::iterator iterator = myList.begin(); advance(iterator, 10); erase(iterator) ; is there an easier way ? like erase(myList[10]); ? tia [Edited by - Toonkides on December 1, 2004 10:07:44 PM]

Share this post


Link to post
Share on other sites
Advertisement
Quote:
Original post by personwholives
afaik, the erase(myList[10]); form is valid.

I'm still learning the STL, so I can't answer the original question. But I'm pretty sure you can't access elements of a list in that fasion. Vector, yes, but not list. A quick test confirms that VC7 does not like "cout << myList[10] << endl;" one bit.

CM

Share this post


Link to post
Share on other sites
i too am only learning stl, but the topic is on STL vector class, so i assumed that myList is a vector. if it is a vector, then the code is valid. if it is a list, then it is not. in either case, we are both correct, just not talking about the same things.

Share this post


Link to post
Share on other sites
???


vector<int> v;

for (unsigned int i = 0; i < 10; ++i)
v.push_back(i);

for (unsigned int j = 0; j < v.size(); ++j)
cout << v[j] << " ";
cout << endl;

vector<int>::iterator it = v.begin();
v.erase(&v[4]);

for (unsigned int k = 0; k < v.size(); ++k)
cout << v[k] << " ";
cout << endl;





This works because vector provides random access. Beware iterator invalidation.

Share this post


Link to post
Share on other sites
You could also do:
vector< int > vec;

for ( int i = 0; i < 10; ++i )
vec.push_back( i );

vec.erase( vec.begin() + 5 ); // change 5 to whichever element you want to remove, starting from 0




Regards,
jflanglois

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • 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!