LoginSignup
5
1

More than 5 years have passed since last update.

.begin()よりもstd::begin()を使うと配列とコンテナを同様に扱える

Last updated at Posted at 2019-04-09

例えば, コンテナの要素に指定した条件を満たす要素が一つでもればtrue, そうでない場合falseを返す関数を作る場合, 以下の様にメンバ関数であるbegin,endを使うと, std::vectorやstd::arrayなど基本的なコンテナクラスには問題なく動きますが通常の配列ではコンパイルエラーとなります.


#include <algorithm>
// コンテナlist中の要素のうちpredicateを満たすものがあればtrue, そうでない場合はfalseを返す
template<class List, class Predicate>
bool any(List&& list, Predicate&& predicate)
{
  return std::find_if(list.begin(), list.end(), predicate) != list.end();
}

int main()
{
  std::vector<int> vec_list = {1, 2, 3, 4, 5};
  std::array<int, 5> array_list = {1, 2, 3, 4, 5};

  any(vec_list, [](int e) {  return e == 2;} );   //  => true
  any(array_list, [](int e) { return e == 2;});   //  => true

  int c_array[] = { 1, 2, 3, 4, 5};
  any(c_array, [](int e) { return e == 2; });     // => コンパイルエラー. c_arrayにbegin(), end()がない
}

というわけで グローバル関数であるstd::begin, std::end関数を使いましょう


// コンテナlist中の要素のうちpredicateを満たすものがあればtrue, そうでない場合はfalseを返す
template<class List, class Predicate>
bool any(List&& list, Predicate&& predicate)
{
  return std::find_if(std::begin(list), std::end(list), predicate) != std::end(list);
}

5
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
1