使用std::find搜索对的向量时忽略其中一个值

Ignoring one of the value when searching the vector of pairs using std::find

本文关键字:一个 搜索 find std 向量 使用      更新时间:2023-10-16

在给定的成对向量中

static std::vector<std::pair<int,int>> v

当我使用std::find 搜索矢量时,如何忽略其中一个值

std::find(v.begin(), v.end(), std::make_pair(first int, /*ignored value*/)) - v.begin();

使用更好的算法:std::find_if:

auto it = std::find_if(v.begin(), v.end(), [first](const std::pair<int, int>& elem){
    return elem.first == first;
});

或者find与范围-v3:的不同风味

auto it = ranges::find(v,
    first,                      // the value
    &std::pair<int, int>::first // the projection
    );