次のようなベクトルがあるとします。
vector< pair<string, pair<int, int> > > cont;
今、私はと等しいcont
elem を見つけたいと思っています。STL が提供するファンクターとアルゴリズム (find_if, is_equal??) を使用して、これを簡単に行うにはどうすればよいでしょうか。(Boost Please も新しい C++ もありません。)first
"ABC"
編集:述語ファンクターを定義せずに行うことは可能ですか?
何かのようなもの
typedef std::pair<std::string, std::pair<int, int> > pair_t;
struct Predicate : public std::unary_function<pair_t, bool>
{
public:
Predicate(const std::string& s):value(s) { }
result_type operator () (const argument_type& pair)
{
return pair.first == value;
}
private:
std::string value;
};
std::vector<pair_t>::const_iterator pos = std::find_if(cont.begin(), cont.end(),
Predicate("ABC"));
またはラムダ (C++11 の場合)。
auto pos = std::find_if(cont.begin(), cont.end(),
[](const std::pair<std::string, std::pair<int, int>>& pair)
{
return pair.first == "ABC";
});
実際、構造体を使わずにそのようなことを行うには、良くない方法が 1 つあります。
typedef std::pair<std::string, std::pair<int, int> > pair_t;
namespace std {
template<>
bool operator ==<> (const pair_t& first, const pair_t& second)
{
return first.first == second.first;
}
}
std::vector<pair_t>::const_iterator pos = std::find_if(cont.begin(), cont.end(),
std::bind2nd(std::equal_to<pair_t>(), std::make_pair("ABC", std::make_pair(1, 2))));
検索よりも高速にする必要がある場合は、検索 (または)
をO(N)
置き換える(または並列を追加する)ことができます。ファンクターは必要ありません。vector
map
O(log N)
O(1)
unordered_map
vector<pair<string, pair<int,int>>> cont {{"ABC",{1,11}}, {"DFG",{2,22}}};
map <string, pair<int,int>> M(cont.begin(), cont.end());
cout << M["ABC"] << endl;
RO ライブラリ(恥ずべきプラグ)を使用すると、次のようになります。
#include <sto/sto.h>
using namespace sto;
...
auto it = cont / (_0=="ABC");
ここでは、/
内部的に呼び出すオーバーロードされた op find_if
; _0
- STO ラムダ式のタプル (またはペア) の最初の要素への参照。_0=="ABC"
- 述語を生成するラムダ式find_if