adding reverse iterator code

This commit is contained in:
Jidong Xiao
2024-02-13 13:41:10 -05:00
parent 0b29ddbbe1
commit aa5bb20b1f
2 changed files with 27 additions and 5 deletions

View File

@@ -24,14 +24,18 @@ properties clear:
```cpp ```cpp
std::list<int> a; std::list<int> a;
unsigned int i; unsigned int i;
for ( i=1; i<10; ++i ) a.push_back( i*i ); for ( i=1; i<10; ++i ){
a.push_back( i*i );
}
std::list<int>::reverse_iterator ri; std::list<int>::reverse_iterator ri;
for( ri = a.rbegin(); ri != a.rend(); ++ri ) for( ri = a.rbegin(); ri != a.rend(); ++ri ){
cout << *ri << endl; std::cout << *ri << std::endl;
}
``` ```
This code will print out the values 81, 64, 49, . . . , 1, in order, on separate lines. Observe the type for the This code will print out the values 81, 64, 49, . . . , 1, in order, on separate lines. You can also compile and run this [example program](reverse_iterator.cpp).
reverse iterator, the use of the functions rbegin and rend to provide iterators that delimit the bounds on
Observe the type for the reverse iterator, the use of the functions rbegin and rend to provide iterators that delimit the bounds on
the reverse iterator, and the use of the ++ operator to take one step backwards through the list. It is very the reverse iterator, and the use of the ++ operator to take one step backwards through the list. It is very
important to realize that rbegin and end are NOT the same thing! One of the challenges here will be important to realize that rbegin and end are NOT the same thing! One of the challenges here will be
determining when to stop (when youve reached the halfway point in the list). You may use an integer determining when to stop (when youve reached the halfway point in the list). You may use an integer

View File

@@ -0,0 +1,18 @@
#include <iostream>
#include <list>
int main(){
std::list<int> a;
unsigned int i;
for ( i=1; i<10; ++i ){
a.push_back( i*i );
}
std::list<int>::reverse_iterator ri;
for( ri = a.rbegin(); ri != a.rend(); ++ri ){
std::cout << *ri << std::endl;
}
return 0;
}