获取STL向量中大于值的元素的所有位置 [英] Get all positions of elements in STL vector that are greater than a value

查看:58
本文介绍了获取STL向量中大于值的元素的所有位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何找到验证某个条件(例如大于)的元素的索引位置.例如,如果我有一个整数值的向量

  vector< int>V; 

V包含值 3 2 5 8 2 1 10 4 7

,我想获取所有大于5的元素的索引位置.我知道 std :: find_if ,但是根据文档,它只是找到满足条件的第一个元素.

解决方案

循环 std :: find_if ,从您上次停止的地方开始.

示例(查看它的工作原理):

  std :: vector< size_t>结果;auto it = std :: find_if(std :: begin(v),std :: end(v),[](int i){return i> 5;});while(它!= std :: end(v)){results.emplace_back(std :: distance(std :: begin(v),it));它= std :: find_if(std :: next(it),std :: end(v),[](int i){return i> 5;});} 

首先,我们用第一个结果设置迭代器.如果找不到,则while循环将永远不会执行.否则,将存储索引位置( std :: distance 本质上是更通用的 it-std :: begin(v)),然后继续搜索.

I would like to know how can I find the index positions of elements that verify a certain condition (for example greater than). For example if I have a vector of int values

vector<int> V;

V contains the values 3 2 5 8 2 1 10 4 7

and I want to get all the index positions of elements that are greater than 5. I know std::find_if but according to the documentation it just finds the first element that satisfies a condition.

解决方案

Loop std::find_if, starting from where you stopped last time.

Sample (see it work):

std::vector<size_t> results;

auto it = std::find_if(std::begin(v), std::end(v), [](int i){return i > 5;});
while (it != std::end(v)) {
   results.emplace_back(std::distance(std::begin(v), it));
   it = std::find_if(std::next(it), std::end(v), [](int i){return i > 5;});
}

First we set up the iterator with the first result. If it's not found, the while loop never executes. Otherwise, the index position is stored (std::distance is basically a more generic it - std::begin(v)), and the search continues onward.

这篇关于获取STL向量中大于值的元素的所有位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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