通过第一个值在向量中找到一对

时间:2017-06-07 05:11:23

标签: c++11 stl

我有一个包含几对(INT,INT)的向量。 我想搜索特定的但我只有一对密钥。 我该如何搜索第二把钥匙?

1 个答案:

答案 0 :(得分: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,其伪代码与我的伪代码完全相同。