Answer to Question #225951 in C++ for Croft

Question #225951

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. 


1
Expert's answer
2021-08-13T16:12:52-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS