This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Thursday, March 23, 2023

Write a program using the algorithm count() to count how many elements in a container have a specified value.

 Here's an example program using the count() algorithm to count the number of occurrences of a specific value in a vector container:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> numbers = { 2, 5, 3, 7, 8, 5, 1, 5, 4 };
    
    // count the number of occurrences of the value 5 in the vector
    int count = count(numbers.begin(), numbers.end(), 5);
    
    cout << "The number of occurrences of 5 in the vector is: " << count << endl;
    
    return 0;
}

Output:

The number of occurrences of 5 in the vector is: 3


Explanation:

  • The program starts by creating a vector named numbers that contains several integer values.
  • The count() algorithm is used to count the number of occurrences of the value 5 in the numbers vector. The function takes three arguments: the beginning and end iterators of the container to search, and the value to count.
  • The count is then stored in an integer variable named count.
  • Finally, the program outputs the count using the cout statement.

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget