Amit Jha Amit Jha - 1 year ago 123
C++ Question

Counting struct elements in 2D vector C++

I have a 2D vector of structures of this type

typedef struct box
int boxVal;
char boxTakenBy;
} box;

I have
defined as:

vector<vector<box> > myvector(10,vector<box>(10))

My goal is to count number of elements with
boxTakenBy == 'X'
. I tried:

int mycount = std::count_if( myvector.begin(), myvector.end(),
[](const box &p ) { return p.boxTakenBy == 'X'; });

I am getting compilation error :

no match for call to ‘<lambda(const box&)>) (std::vector<box >&)

Not sure if my approach is wrong or just the syntax. Please correct if you find any syntax issue or suggest if any better approach is out there.

Answer Source

As mentioned by hauron elements of myvector are not boxes but vector<box>s. So what you need to do it iterate over 2 dimensions of myvector.

You can combine std::accumulate (to accumulate the sum) and std::count_if (to count the inner elements satisfying your condition ( == 'X') to achieve that like so:

#include <vector>
#include <algorithm>
#include <iostream>
#include <numeric>

struct box
    int boxVal;
    char boxTakenBy;

int main(){
  using namespace std;
  vector<vector<box> > myvector(10, vector<box>(10));

  myvector[0][0].boxTakenBy = 'X';
  myvector[2][0].boxTakenBy = 'X';
  myvector[2][7].boxTakenBy = 'X';
  myvector[5][7].boxTakenBy = 's';

  int total_count = std::accumulate(myvector.begin(), myvector.end(), 0,
                                    [](int acc, const vector<box>& curr)
                                      return acc + std::count_if(curr.begin(), curr.end(),
                                        [](const box& b ) { return b.boxTakenBy == 'X'; });

  std::cout << total_count << '\n';


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download