我有一个向量对,例如
std::vector< std::pair <int, double> > vec = { {1, 2.0}, {5, 21.0} };
我想检查此向量是否有一对第一个元素等于5的对,如果是这种情况,那么我想返回该对的第二个元素21.0。如果不是,则返回99.9。
我知道我可以std:find
和家人一起使用,但不确定如何做价值回报部分。例如,以下搜索stackoverflow似乎是一个近似的解决方案:
#include <vector>
#include <algorithm>
double MyFunc(int key) const {
if (std::find(vec.begin(), vec.end(), [&key](std::pair<int, double> const& elem) {
return elem.first == key;
}))
return ???;
else
return 99.9;
}
这是可能的解决方案吗?我应该填写???;
什么?如您所见,我不是C ++等类似程序的资深程序员,因此不胜感激。
auto it = std::find_if(vec.begin(), vec.end(),
[&key](const std::pair<int, double>& elem) {
return elem.first == key;
});
return it != vec.end() ? it->second : 99.9;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句