2012-12-24 53 views
5

說我有一個這樣的載體:C++在一個std ::搜索矢量

vector< pair<string, pair<int, int> > > cont; 

現在我想在cont發現有其first等於"ABC"的ELEM。我怎樣才能用STL提供給我們的函子和算法(find_if,is_equal ??)輕鬆完成這個任務。 (沒有提升請,並沒有新的C++。)

編輯:是否有可能沒有定義一個Predicate仿函數?

+1

你自己說的:'std :: find_if'。你也可以將它與lambda結合起來。 – chris

+0

爲什麼討厭C++ 11? – nikhil

+0

沒有恨,我們愛它! :) – Narek

回答

7

喜歡的東西

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"; 
}); 

真的,有沒有一個不好的方法來做這樣的事情,沒有結構。

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)))); 
+0

請問老版本的標準嗎? – Narek

+0

感謝您提供了很好的解決方案。是否可以在不定義謂詞的情況下執行相同的操作? – Narek

+0

@ Narek,是的,通過硬編碼字符串「ABC」 – ForEveR

1

如果你需要比O(N)搜索速度更快,可以取代vectormap(或添加並行)爲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 library(可恥的插件),這將只是:

#include <sto/sto.h> 
using namespace sto; 

... 
auto it = cont/(_0=="ABC"); 

Here / overloaded op which internal calls find_if; _0 - 在STO lambda表達式中引用元組(或pair)的第一個元素; _0=="ABC" - 生成謂詞的lambda表達式find_if

+0

無序數據結構可能比有序的數據結構,另一方面,它依賴於一個向量及其在存儲器中連續分配的授權,有時可能真的是exp ensive。 – user1849534