在满足条件的std :: vector中查找最后一个元素 [英] Find last element in std::vector which satisfies a condition

查看:217
本文介绍了在满足条件的std :: vector中查找最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个要求来找到向量中小于值的最后一个元素。

I have this requirement to find the last element in the vector which is smaller than a value.

就像find_first_of一样,但是我要倒数第一。我搜索了
,发现没有find_last_of,但是有find_first_of。

Like find_first_of but instead of first i want last. I searched and found that there is no find_last_of but there is find_first_of.

为什么会这样?标准方法是将find_first_of与反向迭代器一起使用吗?

Why is that so? Is the standard way is to use find_first_of with reverse iterators?

推荐答案

使用反向迭代器,例如:

#include <iostream>
#include <vector>

int main()
{
  std::vector<int> v{1,2,42,42,63};
  auto result = std::find_if(v.rbegin(), v.rend(),
                             [](int i) { return i == 42; });

  std::cout << std::distance(result, v.rend()) << '\n';
}

实时演示

这篇关于在满足条件的std :: vector中查找最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆