简体   繁体   中英

Reversing the contents of an std::list

class Print 
   {  
   public:
       void PrintAll() {}
   private:
    std::list<int> mylist;
   };

I see this example question from a C++ language book. And I want to print the internal mylist elements. How can it be done if mylist needs to be reversed, using C++ STL library and using to output the result.

Thanks you very much!

std::list<>::reverse() ?

That said, if you only need to print the list in reverse, you can simply print it using list 's reverse iterators (obtained by std::list<>::rbegin() and std::list<>::rend() ) rather than by using list 's normal iterators. Eg:

// given std::list<int> l;
for (std::list<int>::const_reverse_iterator iter(l.rbegin()), iter_end(l.rend());
        iter != iter_end;
        ++iter)
{
    std::cout << *iter << '\n';
}

You can use the reverse() method on your list.

mylist.reverse();

will reverse the contents of your list and then you can print the same, using iterators.

list<int>::iterator it;
cout << "mylist contains:";
for (it=mylist.begin(); it!=mylist.end(); ++it)
    cout << " " << *it;

You can wrap all the functionality up in your own member function.

iterator simply point to the current element in the list. So, if we write a for loop going from end to beginning, we can print the list in reverse. in the code given below:

    #include <iostream>
    #include <list>

    using namespace std;

    int main()
    {
       std::list<int> ii;
       ii.push_back(1);
       ii.push_back(2);
       ii.push_back(3);
       ii.push_back(4);
       ii.push_back(5);
       for (std::list<int>::iterator it = (ii.begin()); it != (ii.end()) ; ++it)
       {
           cout << (*it) << " ";
       }
       cout << endl;
       for (std::list<int>::iterator it = (--ii.end()); it != (--ii.begin()) ; it--)
       {
           cout << (*it) << " ";
       }
       return 0;
    }

The first for loop prints out the list from front to back while the second one prints from back to front.

您还可以使用容器eglrbegin()和l.rend()提供的反向迭代器,它将向后遍历列表。

Code example for list::reverse

// list_reverse.cpp
// compile with: /EHsc
#include <list>
#include <iostream>

int main( ) 
{
   using namespace std;
   list <int> c1;
   list <int>::iterator c1_Iter;

   c1.push_back( 10 );
   c1.push_back( 20 );
   c1.push_back( 30 );

   cout << "c1 =";
   for ( c1_Iter = c1.begin( ); c1_Iter != c1.end( ); c1_Iter++ )
      cout << " " << *c1_Iter;
   cout << endl;

   c1.reverse( );
   cout << "Reversed c1 =";
   for ( c1_Iter = c1.begin( ); c1_Iter != c1.end( ); c1_Iter++ )
      cout << " " << *c1_Iter;
   cout << endl;
}

And the output will be

c1 = 10 20 30 Reversed c1 = 30 20 10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM