Count elements in a vector that match a target value or condition in C++

C++Server Side ProgrammingProgramming

We are given a vector and the task is to calculate the count of those elements in a vector that matches a target value or condition.

Vectors are sequence containers that can change size. Container is an object that holds data of the same type. Sequence containers store elements strictly in linear sequence.

Vector stores elements in contiguous memory locations and enables direct access to any element using subscript operator []. Unlike arrays, vectors can shrink or expand as needed at run time. The storage of the vector is handled automatically.

To support shrink and expand functionality at runtime, vector containers may allocate some extra storage to accommodate for possible growth thus containers have actual capacity greater than the size. Therefore, compared to array, vector consumes more memory in exchange for the ability to manage storage and grow dynamically in an efficient way.

For Example

Input − vector vec = {1, 2, 3, 4, 4, 4, 4}
      Target = 4
Output − count is: 4

Explanation − in the given vector the target is occurring 4 times so the count is 4

Input − vector vec = {1, 2, 3}
      Target = 4
Output − count is: 0

Explanation − in the given vector the target is occurring 0 times so the count is 0

Approach used in the below program is as follows

  • Input the vector and store it in a vector type variable let’s say vec

  • Set the target value as an integer value

  • Take a temporary variable that will store the count

  • Call the inbuilt count function available in C++ STL and pass vec.begin(), vec.end(), target to the function call

  • Print the result.

Example

 Live Demo

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main(){
   vector<int> myvector{ 1, 2, 3, 4, 4, 4, 4, 4 };
   int target = 4;
   int res = count(myvector.begin(), myvector.end(), target);
   cout << "Target is: " << target << "\nCount is: " << res << endl;
   return 0;
}

Output

If we run the above code we will get the following output −

Target is: 4
Count is: 5
raja
Published on 15-May-2020 12:22:17
Advertisements