how to calculate the number of occurrences of a variable (digit) in a 2D vector in an optimized and fast way using STL?

  2d-vector, c++, count, stl

I have a 2D vector of Integer and want to count how many times certain value is repeated. For example:

I have myvector defined as:

std :: vector <std :: vector <int>> myVector {{{1, 2, 9, 4, 6},
                                       {8, 3, 5, 4, 8},
                                       {4, 1, 9, 1, 7},
                                       {5, 2, 7, 3, 4},
                                       {7, 4, 3, 5, 1};

My goal is to count number of elements where x = 4 for example, and the result return 5:
I tried:

int sum = 0;
for (auto i: myVector) {
     sum + = std :: count (i.begin (), i.end (), 4);

however, I need to run this type of method several times in a realtime application, but the for loop is time consuming, I am trying to minimize the execution time by using the functions of the STL, I have so tried:

   std :: count (myVector.begin (), myVector.end (), 4);

however, this syntax cannot work directly on a 2D vector.

anyone have a solution?

Source: Windows Questions C++

LEAVE A COMMENT