yohhoyの日記

技術的メモをしていきたい日記

非メンバ関数版 begin/end のすゝめ

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