“Some leaders cannot manage – some managers cannot lead” Murray Johannsen
Non-member begin() and end() or C++11 iterator range accrss Sven Johannsen 14.08.2014 C++ User Group...
-
Upload
ambrose-wilkins -
Category
Documents
-
view
213 -
download
0
Transcript of Non-member begin() and end() or C++11 iterator range accrss Sven Johannsen 14.08.2014 C++ User Group...
Non-member begin() and end()or C++11 iterator range accrss
Sven Johannsen14.08.2014
C++ User Group Aachen
Always use nonmember begin(x) and end(x)
“Always use nonmember begin(x) and end(x) (not x.begin() and x.end()), because begin(x) and end(x) are extensible and can be adapted to work with all container types – even arrays – not just containers that follow the STL style of providing x.begin() and x.end() member functions.”
Herb SutterElements of Modern C++ Style
From ISO 14882 - 2011
24.6.5 range access [iterator.range]…template <class C> auto begin(C& c) -> decltype(c.begin());template <class C> auto begin(const C& c) -> decltype(c.begin());
template <class C> auto end(C& c) -> decltype(c.end());template <class C> auto end(const C& c) -> decltype(c.end());…
From Boost
“A Range is a concept similar to the STL Container concept. A Range provides iterators for accessing a half-open range [first,one_past_last) of elements and provides information about the number of elements in the Range. However, a Range has fewer requirements than a Container.”
BoostRange / Overview
Differences between Container and Range
• (STL-) Container• begin() and end() member
functions
• auto it1 = cont.begin();
• auto it2 = cont.end();
• e.g. std::vector, std::list, std::map
Rangenon member begin() and end() functions
auto it1 = begin(cont);
auto it2 = end(cont);
e.g. std::vector, std::list, std::map and double[10], std::valarray
Non Member begin() and end()
Unified iterator access for any containerAddition level of abstraction for an iterator access.
template<class CONT> void foo(const CONT& cont) {for(auto it = begin(cont); it != end(cont); ++it) { cout << *it << " ";}
}
This code runs with any container (if non-member begin() and end() are overloaded).
Non-Member for Non-STL Container
E.g.: Range based for loop for non STL containers
template<class T> CArrayIterator<T> begin(const CArray<T>& arr);template<class T> CArrayIterator<T> end(const CArray<T>& arr); ...CArray<int> arr;...for(int i : arr) { cout << i << " " << endl;}bool sorted = std::is_sorted(begin(arr), end(arr));
C++14
C++14 will also introduce non-member • cbegin(), • cend(), • rbegin(), • rend(), • crbegin() and • crend().