Get all positions of elements in STL vector that are greater than a value(获取 STL 向量中大于某个值的元素的所有位置)
问题描述
我想知道如何找到验证特定条件(例如大于)的元素的索引位置.例如,如果我有一个 int 值向量
vectorⅤ; V 包含值 3 2 5 8 2 1 10 4 7
并且我想获取大于 5 的元素的所有 索引位置.我知道 std::find_if 但根据文档,它只找到满足条件的第一个元素.
Loop std::find_if,从上次停止的地方开始.
示例(查看效果):
std::vector结果;auto it = std::find_if(std::begin(v), std::end(v), [](int i){return i > 5;});而(它!= 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;});} 首先我们用第一个结果设置迭代器.如果没有找到,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 向量中大于某个值的元素的所有位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:获取 STL 向量中大于某个值的元素的所有位置
基础教程推荐
- 提升 ASIO 流缓冲 2021-01-01
- c++ STL设置差异 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
