From aa5bb20b1f7d26055d90476ef603b79f852cad59 Mon Sep 17 00:00:00 2001 From: Jidong Xiao Date: Tue, 13 Feb 2024 13:41:10 -0500 Subject: [PATCH] adding reverse iterator code --- labs/06_lists_iterators/README.md | 14 +++++++++----- labs/06_lists_iterators/reverse_iterator.cpp | 18 ++++++++++++++++++ 2 files changed, 27 insertions(+), 5 deletions(-) create mode 100644 labs/06_lists_iterators/reverse_iterator.cpp diff --git a/labs/06_lists_iterators/README.md b/labs/06_lists_iterators/README.md index 69597eb..d7d508d 100644 --- a/labs/06_lists_iterators/README.md +++ b/labs/06_lists_iterators/README.md @@ -24,14 +24,18 @@ properties clear: ```cpp std::list a; 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::reverse_iterator ri; -for( ri = a.rbegin(); ri != a.rend(); ++ri ) -cout << *ri << endl; +for( ri = a.rbegin(); ri != a.rend(); ++ri ){ + 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 -reverse iterator, the use of the functions rbegin and rend to provide iterators that delimit the bounds on +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). + +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 important to realize that rbegin and end are NOT the same thing! One of the challenges here will be determining when to stop (when you’ve reached the halfway point in the list). You may use an integer diff --git a/labs/06_lists_iterators/reverse_iterator.cpp b/labs/06_lists_iterators/reverse_iterator.cpp new file mode 100644 index 0000000..2a73cd6 --- /dev/null +++ b/labs/06_lists_iterators/reverse_iterator.cpp @@ -0,0 +1,18 @@ +#include +#include + +int main(){ + + std::list a; + unsigned int i; + for ( i=1; i<10; ++i ){ + a.push_back( i*i ); + } + + std::list::reverse_iterator ri; + for( ri = a.rbegin(); ri != a.rend(); ++ri ){ + std::cout << *ri << std::endl; + } + + return 0; +}