Answer to Question #230663 in C++ for Jaguar

Question #230663
(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.
(b) Write a template version of the function count to determine the number of times
a specific value occurs in a vector of any base type and test it by declaring two
or more vectors with different base types and determining how many times a
specific value occurs in these two vectors.
1
Expert's answer
2021-08-29T00:57:30-0400
#include <iostream>
#include <vector>
using namespace std;


template<typename T>
int count(vector<T> v1, T val){
    int n = 0;
    for(auto i = v1.begin(); i != v1.end(); i++)
        if(val == *i) n++;
    return n;
}
int main(){
    vector<int> v1;
    v1.push_back(3);
    v1.push_back(3);
    v1.push_back(3);
    v1.push_back(1);
    v1.push_back(-1);
    v1.push_back(1);
    cout<<1<<" occurs "<<count<int>(v1, 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