a) Write a function called count to determine the number of times a specific value occurs in a vector of integers.
The function should receive two parameters: the vector to be searched (v) and the value to search for (val). count should return the number of times val occurs in vector v. Test your function count in a program by declaring a vector and initializing it, and then call function count to determine how many times a specific value occurs in the vector.
#include <iostream>
#include <vector>
using namespace std;
template<typename T>
int count(vector<T> v, T val){
int c = 0;
for(auto i = v.begin(); i != v.end(); i++)
if(val == *i) c++;
return c;
}
int main(){
vector<int> v;
v.push_back(1);
v.push_back(3);
v.push_back(4);
v.push_back(1);
v.push_back(-1);
v.push_back(1);
cout<<1<<" occurs "<<count<int>(v, 1)<<" times";
return 0;
}
Comments
Leave a comment