STL Vector class : deleting elements of,
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]
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
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.
???
This works because vector provides random access. Beware iterator invalidation.
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.
You could also do:
Regards,
jflanglois
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
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement