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
|
#include <iostream>
#include <vector>
#include <iterator>
template < typename ITERATOR > requires requires( ITERATOR i ) { *i = 1 ; }
void foo( ITERATOR iter )
{
ITERATOR saved = iter ;
*iter = 10 ;
*iter = 20 ;
*saved = 30 ;
}
int main()
{
std::vector<int> vec{ 0, 1, 2, 3, 4, 5 } ;
const auto forward_iterator = vec.begin() ;
foo( forward_iterator ) ; // Forward iterators can read or write to the same element multiple times.
// foo assigns to the same value - the one 'pointed to' by the iterator - three times
std::cout << vec.front() << '\n' ; // 30
const auto output_iterator = std::back_inserter(vec) ;
foo(output_iterator) ; // we may assign to a *given value* of an output iterator only once
// foo assigns to *three different values* of the output iterator
// (adds three more items to the back of the container; ie. adds 10, 20 and 30)
std::cout << vec.size() << '\n' ; // 9 ie. vec contains { 0, 1, 2, 3, 4, 5, 10, 20, 30 }
}
| |