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
|
#include <vector>
#include <list>
int main()
{
// add 5 to every element in a sequence
{
int seq[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 } ;
typedef int* pointer ;
for( pointer ptr = seq+0 ; // 0. start by intialising a pointer
// to point to the first element
ptr != seq+10 ; // 4. if we have gone past the last element, break
++ptr ) // 3. move the pointer to point to the next element
{
int& v = *ptr ; // 1. dereference the pointer to get the pointed element
v += 5 ; // 2. do something with it
}
}
{
std::vector<int> seq = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 } ;
typedef std::vector<int>::iterator pointer ;
for( pointer ptr = seq.begin() ; // 0. start by intialising a 'pointer'
// to 'point' to the first element
ptr != seq.end() ; // 4. if we have gone past the last element, break
++ptr ) // 3. move the 'pointer' to 'point' to the next element
{
int& v = *ptr ; // 1. dereference the 'pointer' to get the 'pointed' element
v += 5 ; // 2. do something with it
}
}
{
std::list<int> seq = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 } ;
typedef std::list<int>::iterator pointer ;
for( pointer ptr = seq.begin() ; // 0. start by intialising a 'pointer'
// to 'point' to the first element
ptr != seq.end() ; // 4. if we have gone past the last element, break
++ptr ) // 3. move the 'pointer' to 'point' to the next element
{
int& v = *ptr ; // 1. dereference the 'pointer' to get the 'pointed' element
v += 5 ; // 2. do something with it
}
}
}
|