2012年11月13日(火) [長年日記]
■ [c++] boost::bindは演算子と組み合わせられる
std::find_if( first, last, bind( &X::name, _1 ) == "Peter" || bind( &X::name, _1 ) == "Paul" );
みたいに書けると知らなかったのでメモ。上の例はboostのドキュメントにあったもの。
For convenience, the function objects produced by bind overload the logical not operator ! and the relational and logical operators ==, !=, <, <=, >, >=, &&, ||.
とのこと。サンプルコードをメモ。
#include <algorithm>
#include <iostream>
#include <vector>
#include <boost/bind.hpp>
class A {
int a;
public:
A(int a) : a(a) {}
int get() const { return a; }
};
int main() {
std::vector<A> v;
v.push_back(A(1));
v.push_back(A(2));
v.push_back(A(3));
std::vector<A>::iterator it =
std::find_if(v.begin(), v.end(), boost::bind(&A::get, _1) == 2);
if (it == v.end()) {
std::cout << "not found" << std::endl;
} else {
std::cout << it->get() << std::endl;
}
}
これで「2」と出力される。
C++11のbindでもできるのかは知らない。
[ツッコミを入れる]