C++ STLでfind_ifとファンクタの組み合わせで使う

==演算子をオーバーライドできない場合にstd::findの代わりとして, std::find_ifを使いたい. std::find_ifは3番目の引数として値そのものの代わりに条件を返す関数を与える.

これは例えば関数を用いて以下のように書ける(多分).

typedef std::vector<std::pair<int, int> > container_type

bool cmp(container_type::value_type elem)
{
  return (elem.second == 0);
}

int main()
{
  container_type cont;

  ; // initialize the container

  container_type::const_iterator i(
    std::find_if(cont.begin(), cont.end(), cmp));
  return 0;
}

要素であるstd::pairの2つ目の値が0と等しいものを探す, というような場合でした. ただこれだと, 値がxと等しいものを探す場合に対応しようとすると大変ですので, cmp関数をファンクタ(関数オブジェクト)化してみました.

typedef std::vector<std::pair<int, int> > container_type

class second_element_comparator
  : public std::unary_function<container_type::value_type, bool>
{
public:

  second_element_comparator(
    container_type::value_type::second_type const& target)
    : target_(target)
  {}

  bool operator()(container_type::value_type elem)
  {
    return (elem.second == target_);
  }

protected:

  container_type::value_type::second_type target_;
}

int main()
{
  container_type cont;

  ; // initialize the container

  const int target(0);
  second_element_comparator cmp(target);
  container_type::const_iterator i(
    std::find_if(cont.begin(), cont.end(), cmp));
  return 0;
}

動くかどうか試していませんが, このような感じで動くでしょう. さらにテンプレート化などすると汎用的なコードが書けて便利です.

ヘッダファイルは適当にインクルードする必要があります(vector, algorithm, functionalあたりでしょうか).

http://c.keicode.com/stl/find-if.php
http://www.kab-studio.biz/Programing/Codian/STL/03.html