# STL Vector class : deleting elements of,

## 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 on other sites
afaik, the erase(myList[10]); form is valid.

##### Share on other sites
Quote:
 Original post by personwholivesafaik, 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 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 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 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

## Create an account

Register a new account

• ## Partner Spotlight

• ### Forum Statistics

• Total Topics
627689
• Total Posts
2978659

• 18
• 14
• 12
• 10
• 12