C++ Tutorial/list/list begin end

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

Accessing the Front and Back of a List with for loop

<source lang="cpp">#include <algorithm>

  1. include <iostream>
  2. include <list>

using namespace std; int main( ) {

  const char* name_data[] = { "A", "B","C", "D", "E","F", "G" };
  const bool girl_data[] = { true, true, false, false, true, true, true };
  const int num_graduates = sizeof( girl_data ) / sizeof( girl_data[0] );
  list< pair< string, bool > > graduate;
  for( int i = 0; i < num_graduates; ++i )
     if( girl_data[i] )
        graduate.push_front(
           make_pair( name_data[i], girl_data[i] ) );
     else
        graduate.push_back(
           make_pair( name_data[i], girl_data[i] ) );

}</source>

Accessing the Front and Back of a List with while loop

<source lang="cpp">#include <algorithm>

  1. include <iostream>
  2. include <list>

using namespace std; int main( ) {

  const char* name_data[] = { "A", "B","C", "D", "E","F", "G" };
  const bool girl_data[] = { true, true, false, false, true, true, true };
  const int num_graduates = sizeof( girl_data ) / sizeof( girl_data[0] );
  list< pair< string, bool > > graduate;
  while( !graduate.empty() )
  {
     cout << graduate.front().first;
     graduate.pop_front();
     if( !graduate.empty() )
     {
       cout << " and " << graduate.back().first;
       graduate.pop_back();
     }
     cout << endl;
  }

}</source>

end() is the pointer to the end of a list

<source lang="cpp">#include <iostream>

  1. include <list>

using namespace std;

int main() {

 list<int> lst;
 int i;
  
 for(i=0; i<10; i++) lst.push_back(i);
  
 cout << "List printed forwards:\n";
 list<int>::iterator p = lst.begin();
 while(p != lst.end()) {
   cout << *p << endl;
   p++;
 }
  
 cout << "List printed backwards:\n";
 p = lst.end();
 while(p != lst.begin()) {
   p--;
   cout << *p << " ";
 }
  
 return 0;

}</source>

list.begin and list.end

<source lang="cpp">#include <iostream>

  1. include <list>

using namespace std; int main() {

 list<int> lst; // create an empty list
 int i;
 for(i=0; i<10; i++) lst.push_back(i);
 cout << "List printed forwards:\n";
 list<int>::iterator p = lst.begin();
 while(p != lst.end()) {
   cout << *p << " ";
   p++;
 }
 cout << "\n\n";
 cout << "List printed backwards:\n";
 p = lst.end();
 while(p != lst.begin()) {
   p--; // decrement pointer before using
   cout << *p << " ";
 }
 return 0;

}</source>

List printed forwards:
0 1 2 3 4 5 6 7 8 9
List printed backwards:
9 8 7 6 5 4 3 2 1 0