2.5.1 Beginning and End of Sequence

What was the problem

All containers from the STL have a begin() and end() member function to get an iterator on the first element in the sequence or, respectively, just after the last element. Unfortunately, there is no such function for the most basic sequences, i.e. C-like arrays, so code like that was sure to fail before C++11:

template<typename Sequence, typename T> 
void replace_existing 
(Sequence& s, const T& old_value, const T& new_value) 
{ 
  *std::find(s.begin(), s.end(), old_value) = new_value; 
} 
 
void foo() 
{ 
  int a[] = { 1, 4, 3 }; 
  replace_existing(a, 4, 2); 
}
How the Problem is Solved

PIC <iterator>

Fortunately, C++11 introduces the std::begin() and std::end() free functions which accepts a C-like array5. Now, this code will work in all cases:

template<typename Sequence, typename T> 
void replace_existing 
(Sequence& s, const T& old_value, const T& new_value) 
{ 
  *std::find(std::begin(s), std::end(s), old_value) = new_value; 
} 
 
void foo() 
{ 
  int a[] = { 1, 4, 3 }; 
  replace_existing(a, 4, 2); 
}

5as long as we include <array>