Search indexes of all occurrences of an element in a vector

Suppose I have a vector A = {1 0 1 1 0 0 0 1 0} . Now I want to get the indices 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 the start:

 std::vector<int>::iterator iter = std::find_if(A.begin(), A.end(), 0); B = std::distance(A.begin(), iter); 
+7
source share
2 answers

Just call std::find_if again, with the previously returned iterator (plus one) as the start. Loop until std::find_if returns A.end() .


Code example

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

Try this: char c: the element whose indexes you want to get. I used a string, but the same code will work fine with a vector. Century stores all found indexes.

 std::vector<int> getIndex(string s, char c) { std::vector<int> vecky; for (int i = 0; i != s.length(); i++) { if (s[i] == c) { vecky.push_back(i); } } return vecky; } 
0
source

Source: https://habr.com/ru/post/975290/


All Articles