Find all occurrences

Say I'm given a std::list or std::vector. After taking some user inputs the vector is {1,3,5,6,5,3,4,5}. I want to return ALL the occurrences of 5 in the list. Note that all the elements are integers. The answer should be 2,4,7, as those are the indexes(using 0 indexing). Is there any function to do this?
Last edited on
No, but you could soon write one.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <vector>
using namespace std;

template<typename T> ostream & operator << ( ostream &out, const vector<T> &V )
{
   for ( auto e : V ) out << e << ' ';
   return out;
}


template<typename T> vector<int> allOccurences( const vector<T> &V, T value )
{
   vector<int> result;
   for ( int i = 0; i < V.size(); i++ ) if ( V[i] == value ) result.push_back( i );
   return result;
}


int main()
{
   vector<int> V = { 1, 3, 5, 6, 5, 3, 4, 5 };
   int value = 5;
   cout << "Original vector: " << V << '\n';
   cout << "Positions of " << value << " are: " << allOccurences( V, value ) << '\n';
}


Original vector: 1 3 5 6 5 3 4 5 
Positions of 5 are: 2 4 7
Last edited on
Topic archived. No new replies allowed.