gpt4 book ai didi

c++ - 如何对 vector 使用查找算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:32:06 26 4
gpt4 key购买 nike

如果 vector 的元素是类型,比如vector<pair<int, double>> .我想让查找算法专注于 vector 的第一个元素。我该怎么做?

比如下面是我的数据:

<1, 2>

<3, 5>

<3, 4>
...

我想要在第一列中查找 1。

谢谢,

最佳答案

特意让答案通用:

template <typename K>
struct match_first
{
const K _k; match_first(const K& k) : _k(k) {}
template <typename V>
bool operator()(const std::pair<K, V>& el) const
{
return _k == el.first;
}
};

像这样使用它,例如

it = std::find_if(vec.begin(), vec.begin(), match_first<int>(1));

if (it!=vec.end())
{
// found
}

关于c++ - 如何对 vector 使用查找算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5917877/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com