C++11では新しく非メンバ関数のstd::begin
, std::end
が導入された。Elements of Modern C++ Style では、コンテナクラスc
のメンバ関数c.begin()
, c.end()
ではなく、常に非メンバ関数版を利用するよう推奨している。
#include <vector> std::vector<int> v; int a[100]; std::sort( std::begin(v), std::end(v) ); // コンテナ std::sort( std::begin(a), std::end(a) ); // C配列
正直、C配列(T[]
型)を使うくらいならstd::array
を使うべきな気がする。どちらかというと非STLコンテナを汎用アルゴリズムに適合させる仕組みかも。
// アルゴリズム template <class C> bool has_duplicated(C& c) { std::sort(begin(c), end(c)); auto i = std::adjacent_find(begin(c), end(c)); return (i != end(c)); } // 自前コンテナクラス class MyContainer { /* begin(),end()メンバ関数を持たない*/ }; IteratorOfMyContainer begin(MyContainer&) { /*...*/ } IteratorOfMyContainer end(MyContainer&) { /*...*/ } MyContainer data; bool b = has_duplicated(data);
N3337 24.6.5/p1より引用。
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>
.
関連URL