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

Iterate over columns in C++ matrix

I want to iterate over rows and columns in std::vector<std::vector<int>> matrix and get their sum.

I know that I can do this in nested loop, but here is my question. Can I use

int val_sum = 0;
std::for_each(matrix_[row].begin(),matrix_[row].end(),[&](int x) {  val_sum += x;});

for columns and how to do that?

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

>Solution :

The analogous way of your proposal is to iterate the matrix rows and accumulate the elements in the given column.

int val_sum = 0;
std::for_each(matrix.begin(),matrix.end(),[&](std::vector<int> &row) {  val_sum += row[column];});

But I would still prefer to use the c++11 loop version

int val_sum = 0;
for ( const std::vector<int> &row : matrix )
   val_sum += row[column];
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