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.
T开发者_如何转开发hanks 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. E.g.:
// 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.
You can also use reverse iterators provided by the container e.g. l.rbegin() and l.rend() and that will iterate through the list backwards.
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
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.
精彩评论