I have an algorithm to pick up and sum up the specific data from a 2-dimensional array at a time, which was done with the following 2-fold loop
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <vector>
#include <cmath>
using namespace std;
int main(int argc, char* argv[])
{
double data[2000][200];
double result[200];
int len[200];
vector< vector<int> > index;
srand (time(NULL));
// initialize data here
for (int i=0; i<2000; i++) for (int j=0; j<200; j++) data[i][j] = rand();
// each index element contains some indices for some elements in data, each index elements might have different length
// len[i] tell the size of vector at index[i]
for (int i=0; i<200; i++)
{
vector<int> c;
len[i] = (int)(rand()%100 + 1);
c.reserve(len[i]);
for (int j=0; j<len[i]; j++)
{
int coord= (int)(rand()%(200*2000));
c.push_back(coord);
}
index.push_back(c);
}
for (int i=0; i<200; i++)
{
double acc=0.0;
for (int j=0; j<index[i].size(); j++) acc += *(&data[0][0] + (int)(index[i][j]));
result[i] = acc;
}
return 0;
}
Since this algorithm will be applied to a big array and the 2-fold might be executed in quite long time. I am thinking if stl algorithm will help this case but stl is so far too abstract for me and I don't know how to use that in 2-fold loop. Any suggestion or idea is more then welcomed.
Following other posts and information I found online, I am trying to use for_each to solve the issue
double sum=0.0;
void sumElements(const int &n)
{
sum += *(&data[0][0] + n);
}
void addVector(const vector<int>& coords)
{
for_each( coords.begin(), coords.end(), sumElements)
}
for_each( index.begin(), index.end(), addVector);
But this code have two issues. Firstly, it doesn't compile on void sumElements(const int &n), many error message comes out. Second, even it works it won't store the result to the right place. For the first for_each, my intention is to enumerate each index, so to calculate the corresponding sum and store the sum as the corresponding element of results array.