Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use std::acumulate for matrix

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


using matrix = std::vector<std::vector<int>>;

int main()
{
    matrix mtx{5, std::vector<int>(5)};

    int sum = 0;
    for (const auto i : mtx) // can be avoided ? 
    sum += std::accumulate(i.begin(), i.end(), 0, 
        [](int a, int b){a > 0 ? a + b : a;});

}

I want to use std::accumulate for std::vector<std::vector<int>> but I am curious if I can avoid the loop. Also I want to know if the last argument is ok.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Based on your lambda, looks like you want to just sum the positive entries:

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

using Number = int;
using Matrix = std::vector<std::vector<Number>>;

int main() {
  Matrix mtx{5, std::vector<Number>(5, 1)};

  Number sum_positives = std::accumulate(
      mtx.begin(), mtx.end(), Number(0), [](Number const acc, auto const &v) {
        return std::accumulate(
            v.begin(), v.end(), acc,
            [](Number const a, Number const b) { return b > 0 ? a + b : a; });
      });

  std::cout << sum_positives << std::endl;  // 25
  return 0;
}

Don’t forget that the lambda you pass to std::accumulate() must return a value.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading