Tutorial by Examples

// This creates an array with 5 values. const int array[] = { 1, 2, 3, 4, 5 }; #ifdef BEFORE_CPP11 // You can use `sizeof` to determine how many elements are in an array. const int* first = array; const int* afterLast = first + sizeof(array) / sizeof(array[0]); // Then you can iterate ov...
Iterators are Positions Iterators are a means of navigating and operating on a sequence of elements and are a generalized extension of pointers. Conceptually it is important to remember that iterators are positions, not elements. For example, take the following sequence: A B C The sequence co...
If we want to iterate backwards through a list or vector we can use a reverse_iterator. A reverse iterator is made from a bidirectional, or random access iterator which it keeps as a member which can be accessed through base(). To iterate backwards use rbegin() and rend() as the iterators for the e...
begin returns an iterator to the first element in the sequence container. end returns an iterator to the first element past the end. If the vector object is const, both begin and end return a const_iterator. If you want a const_iterator to be returned even if your vector is not const, you can use ...
An iterator to the first element in the container. If a map object is const-qualified, the function returns a const_iterator. Otherwise, it returns an iterator. // Create a map and insert some values std::map<char,int> mymap; mymap['b'] = 100; mymap['a'] = 200; mymap['c'] = 300; // It...
Stream iterators are useful when we need to read a sequence or print formatted data from a container: // Data stream. Any number of various whitespace characters will be OK. std::istringstream istr("1\t 2 3 4"); std::vector<int> v; // Constructing stream iterators and copyi...
A common pattern in other languages is having a function that produces a "stream" of objects, and being able to use loop-code to loop over it. We can model this in C++ as template<class T> struct generator_iterator { using difference_type=std::ptrdiff_t; using value_type=T; ...

Page 1 of 1