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);
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.
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++;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With