dcsimg
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

To Iterate Is Human, to Range Is Divine

The tedium, security hazards, and adverse performance effects of using a pair of iterators to designate the beginning and end of a sequence can all be avoided by switching to ranges—objects that bundle pairs of iterators.


advertisement
ost Standard Library algorithms operate on sequences whose boundaries are designated by a pair of iterators: one iterator marks the beginning of the sequence and another marks its end. Combining such a pair of iterators into a single object has several advantages in terms of code simplification, safety, and performance. The following sections will explain how to use the new C++09 range library and show some of its advantages.


The following Standard Library algorithms, which I have selected randomly from the <algorithm> header, exhibit a recurring pattern of verbosity and tedium:


template <class ForwardIterator, class T>
  void replace(ForwardIterator first,
               ForwardIterator last,
               const T& old_value,
               const T& new_value);

template <class InputIterator, class T>
  InputIterator find(InputIterator first, 
                     InputIterator last,
                     const T& value);

template<class InputIterator, class OutputIterator>
  OutputIterator copy(InputIterator first, 
                      InputIterator last,
			       OutputIterator result);
These algorithms, as well as std::sort, std::remove, and so forth, represent the beginning and the end of the sequence on which they operate by a pair of iterators.


Why not combine these two iterators into a single object? That's exactly what a std::range does—it combines two iterators into a single compact and efficient object.



Thanks for your registration, follow us on our social networks to keep up-to-date