C++/List/list erase

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Demonstrating the STL list erase function

<source lang="cpp">

  1. include <iostream>
  2. include <cassert>
  3. include <list>
  4. include <string>
  5. include <algorithm>

using namespace std;

int main() {

 string s("remembering");
 list<char> list1(s.begin(), s.end());
 list<char>::iterator j;
 j = find(list1.begin(), list1.end(), "i");
 list1.erase(j++);
 list<char>::iterator i;
 for (i = list1.begin(); i != list1.end(); ++i)
   cout << *i << " ";
 list1.erase(j++);
 for (i = list1.begin(); i != list1.end(); ++i)
   cout << *i << " ";
 list1.erase(j++);
 for (i = list1.begin(); i != list1.end(); ++i)
   cout << *i << " ";
 list1.erase(list1.begin());
 for (i = list1.begin(); i != list1.end(); ++i)
   cout << *i << " ";
 list1.erase(list1.begin());
 for (i = list1.begin(); i != list1.end(); ++i)
   cout << *i << " ";
 return 0;

}

/* 

r e m e m b e r n g

r e m e m b e r g

r e m e m b e r

e m e m b e r

m e m b e r

*/       
   
 </source>


keep only the top 3 salespeople

<source lang="cpp">

  1. include <algorithm>
  2. include <functional>
  3. include <iostream>
  4. include <iterator>
  5. include <list>

using namespace std; class Employee {

  public:
  Employee( const string& name = "", int sales = 0,int district = 0 );
  bool operator>( const Employee& rhs ) const;
  void print() const;
  private:
  int district_;
  string name_;
  int sales_;

}; inline Employee::Employee( const string& name, int sales,

  int district )
  : district_( district ), name_( name ), sales_( sales )

{} inline bool Employee::operator>( const Employee& rhs ) const { return sales_ > rhs.sales_; } inline void Employee::print() const { cout << name_ << " from District " << district_

  << " has sales of $" << sales_ << endl;

} int main( ) {

  list<Employee> list1;
  list1.push_back( Employee( "A", 3, 1 ) );
  list1.push_back( Employee( "B", 4, 1 ) );
  list1.push_back( Employee( "C", 8, 1 ) );
  list1.sort( greater<Employee>() );
  for_each( list1.begin(), list1.end(), mem_fun_ref( &Employee::print ) );
  const int top_positions = 3;
  list<Employee>::iterator position = list1.begin();
  advance( position, top_positions );
  list1.erase( position, list1.end() );
  for_each( list1.begin(), list1.end(),mem_fun_ref( &Employee::print ) );

}


 </source>