2017-06-07 65 views
0

我有一個包含多對(INT,INT)的向量。 我想搜索一個特定的,但我只有一對關鍵。 我應該如何搜索第二個密鑰?按照第一個值在向量中查找一對

+0

['std :: find_if'](http://en.cppreference.com/w/cpp/algorithm/find)應該適用於這樣的搜索。 –

+1

https://stackoverflow.com/questions/12008059/find-if-and-stdpair-but-just-one-element – user2181624

+1

[find \ _if和std :: pair,但只是一個元素](https: //stackoverflow.com/questions/12008059/find-if-and-stdpair-but-just-one-element) – luk32

回答

0

您可以使用下面的算法(僞代碼):

let vec be the input vector 
let key be the value that you are searching 
for each pair p in vec 
    let p_1 be p.first 
    if p_1 == key 
     return you have found the key 

這裏是提取可重用的組件功能的方法:

find_if(beg, end, predicate): 
    let beg be an iterator to the beginning of a sequence 
    let end be an iterator to the end of a sequence 
    let predicate be a function from container element to boolean 
    for each iterator in beg...end 
     let element be what the iterator points to 
     if predicate(element) 
      return iterator 

現在,你可以自定義一個謂詞函數:

my_predicate(p): 
    let p be a pair 
    let p_1 be p.first 
    let key be the value that you are searching 
    return p_1 == key 

並使用find_if:

let vec be the input vector 
found_iterator = find_if(begin(vec), end(vec), my_predicate) 

恰巧,C++標準庫包含std::find_if,它與我的僞代碼具有非常相同的接口。

相關問題