查找向量中所有出现的元素的索引 [英] Finding the indexes of all occurrences of an element in a vector

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

问题描述

假设我有一个向量 A = {1 0 1 1 0 0 0 1 0}.现在我想获取作为另一个向量 B 返回的所有出现的 0 的索引.

Suppose I have a vector A = {1 0 1 1 0 0 0 1 0}. Now I want to get the indexes of all occurrences of 0 returned as another vector B.

template< class InputIt, class T>
std::vector<int> IndicesOf(InputIt first, InputIt last, const T& value) {

}

这是一个开始:

std::vector<int>::iterator iter = std::find_if(A.begin(), A.end(), 0);
B = std::distance(A.begin(), iter);

推荐答案

只需再次调用 std::find_if ,以之前返回的迭代器(加一)为开头.循环执行直到 std::find_if 返回 A.end().

Just call std::find_if again, with the previously returned iterator (plus one) as the beginning. Do in a loop until std::find_if returns A.end().

示例代码

#include <algorithm> //find_if

bool isZero(int x){
    return x == 0;
}

std::vector<int>::iterator iter = A.begin();
while ((iter = std::find_if(iter, A.end(), isZero)) != A.end())
{
    // Do something with iter

    iter++;
}

这篇关于查找向量中所有出现的元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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