Are the non-member function templates begin(container)
and end(container)
part of C++0x? If so, in which header file do they live?
Asked
Active
Viewed 946 times
6
![](../../users/profiles/252000.webp)
fredoverflow
- 237,063
- 85
- 359
- 638
1 Answers
8
Yes, but just as swap
is defined in different places and depends on ADL, so are begin
and end
. The 'generic' versions are defined in <iterator>
:
// 24.6.5, range access:
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());
template <class T, size_t N> T* begin(T (&array)[N]);
template <class T, size_t N> T* end(T (&array)[N]);
Note also that 24.6.5 says:
In addition to being available via inclusion of the
<iterator>
header, the function templates in 24.6.5 are available when any of the following headers are included:<array>
,<deque>
,<forward_list>
,<list>
,<map>
,<regex>
,<set>
,<string>
,<unordered_map>
,<unordered_set>
, and<vector>
.
![](../../users/profiles/277176.webp)
Yakov Galka
- 61,035
- 13
- 128
- 192
-
Out of sheer curiosity: Why would someone use them instead of `c.begin()`? – Karl von Moor Jul 30 '11 at 11:03
-
7@Karl because that's not possible for all types you can iterate over. That if `c` is an array. – Johannes Schaub - litb Jul 30 '11 at 11:10
-
@Karl: although the prefix syntax becomes unreadable when chained (`f(g(h(x)), a(b(y)))`), it's extensible and looks much more like functional programming. It only remains to add open multi-methods to the language. – Yakov Galka Jul 30 '11 at 12:02
-
1@Karl: Atop of what Johannes and ybungalobill said: Every C++ programmer (especially those coming from Java, C# and the like) should have read [this classic article](http://drdobbs.com/184401197) by Scott Meyers. – sbi Jul 30 '11 at 12:49
-
@Karl: For a situation where global begin/end are indispensable, see the [pretty printer](http://louisdx.github.com/cxx-prettyprint/), or [STL #6](http://channel9.msdn.com/Shows/Going+Deep/C9-Lectures-Stephan-T-Lavavej-Advanced-STL-6-of-n) (from where I got the idea). – Kerrek SB Jul 30 '11 at 14:22