Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the indexes of all occurrences of an element in a vector

Tags:

c++

vector

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) {

}

Here is a start:

std::vector<int>::iterator iter = std::find_if(A.begin(), A.end(), 0);
B = std::distance(A.begin(), iter);
like image 869
Hum Avatar asked Sep 15 '14 10:09

Hum


People also ask

Is there an R function for finding the index of an element in a vector?

Use the match() Function to Find the Index of an Element in R. The match() function is very similar to the which() function. It returns a vector with the first index (if the element is at more than one position as in our case) of the element and is considered faster than the which() function.


1 Answers

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().


Sample code

#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++;
}
like image 82
Some programmer dude Avatar answered Sep 22 '22 09:09

Some programmer dude