1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
|
#include <iostream>
#include <list>
#include <iterator>
struct example { int value ; /* ...... */ };
std::ostream& operator<< ( std::ostream& stm, example ex )
{ return stm << '{' << ex.value << '}' ; }
std::list<example> my_list { {12}, {83}, {54}, {76}, {21}, {90}, {64}, {38}, {47}, {61} } ;
void example( std::ostream& os )
{
// note: the name of the function'example' hides the name of the type 'example'
// std::list<example>::iterator dummy; // *** error: 'example' is not the name of a type
std::list< struct example >::iterator dummy ; // fixed: use an extended type specifier
// iterate through the list using iterators (print every element in the list)
for( dummy = my_list.begin(); dummy != my_list.end(); ++dummy ) os << *dummy << ' ' ;
os << '\n' ;
// iterate through the list using iterators (print every element in the list)
for( dummy = my_list.begin(); dummy != my_list.end(); std::advance(dummy,1) ) os << *dummy << ' ' ;
os << '\n' ;
// iterate through the list using iterators (let the compiler figure out the type of the terator)
for( auto iter = my_list.begin(); iter != my_list.end(); ++iter ) os << *iter << ' ' ;
os << '\n' ;
// iterate through the list using iterators (let the compiler figure out the type of the terator)
for( auto iter = my_list.begin(); iter != my_list.end(); iter = std::next(iter) ) os << *iter << ' ' ;
os << '\n' ;
// iterate through the list using iterators (let the compiler figure out how to write the loop)
for( const auto& ex : my_list ) os << ex << ' ' ;
os << '\n' ;
// iterate through the list using iterators (print every element in an even position in the list)
for( auto iter = my_list.begin(); iter != my_list.end(); ++iter )
{
os << *iter++ << " " ;
if( iter == my_list.end() ) break ;
}
os << '\n' ;
// iterate through the list using iterators (print every element in an even position in the list)
for( auto iter = my_list.begin(); iter != my_list.end(); iter = std::next(iter) )
{
os << *iter << " " ;
std::advance(iter,1) ;
if( iter == my_list.end() ) break ;
}
os << '\n' ;
// iterate through the list using iterators (print every element in an odd position in the list)
for( auto iter = my_list.begin(); iter != my_list.end(); ++iter )
{
++iter ;
if( iter == my_list.end() ) break ;
os << " " << *iter << ' ' ;
}
os << '\n' ;
// iterate through the list using iterators (print every element in an odd position in the list)
for( auto iter = my_list.begin(); iter != my_list.end(); std::advance(iter,1) )
{
iter = std::next(iter) ;
if( iter == my_list.end() ) break ;
os << " " << *iter << ' ' ;
}
os << '\n' ;
}
int main()
{
example(std::cout) ;
}
|