1. 程式人生 > >c++ list中erase()操作

c++ list中erase()操作

#include <list>
#include <iostream>

int main( ) 
{
   using namespace std;
   list <int> c1;
   list <int>::iterator Iter;
   
   c1.push_back( 10 );
   c1.push_back( 20 );
   c1.push_back( 30 );
   c1.push_back( 40 );
   c1.push_back( 50 );
   cout << "The initial list is:";
   for ( Iter = c1.begin( ); Iter != c1.end( ); Iter++ )
      cout << " " << *Iter;
   cout << endl;

   c1.erase( c1.begin( ) );
   cout << "After erasing the first element, the list becomes:";
   for ( Iter = c1.begin( ); Iter != c1.end( ); Iter++ )
      cout << " " << *Iter;
   cout << endl;
   Iter = c1.begin( );
   Iter++;
   c1.erase( Iter, c1.end( ) );
   cout << "After erasing all elements but the first, the list becomes: ";
   for (Iter = c1.begin( ); Iter != c1.end( ); Iter++ )
      cout << " " << *Iter;
   cout << endl;
}
#include <iostream>
#include <list>
using namespace std;
int main(){
	list<int> a;
	list<int>::iterator Iter;
	for(int i=0;i<10;i++){
		a.push_back(i);
	}
	cout<<"初始時:"<<endl;
	for(Iter=a.begin();Iter!=a.end();Iter++){
		cout<<*Iter<<"     ";
	}
	cout<<endl;
	for(Iter=a.begin();Iter!=a.end();Iter++){
		if(4==*Iter){
			a.erase(Iter++);
		}
	}
	cout<<"刪除後:"<<endl;
	for(Iter=a.begin();Iter!=a.end();Iter++){
		cout<<*Iter<<"     ";
	}
	system("pause");
	return 0;
}


(未完待續)