Two dimensional array processing using std::for_each

#include <vector>
#include <iostream>
#include <algorithm>
 
typedef std::vector<std::vector<short> > table_t;
 
struct process_col { 
      int row_index;
      int col_index;
      process_col(int r) : row_index(r), col_index(0){}
      void operator()(short & data) {
           std::cout << "Value at (" <<row_index <<"," << col_index << ") is " << data << std::endl; 
           col_index++;
      }
}; 
struct process_row {
      int row_index;
      process_row() : row_index(0){}
      void operator()(std::vector<short> & row){
         std::for_each(row.begin(), row.end(), process_col(row_index));
         row_index++;
      }
}; 
int main ( int argc , char **argv) {
    table_t t = table_t(5, std::vector<short>(5));
    int counter = 0;
    for (size_t row = 0; row < 5; ++row)
           for (size_t col = 0; col < 5; ++col)
               t[row][col] = counter++;
 
    std::for_each( t.begin(), t.end(), process_row());
    return 0;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s