what a weird topic to talk about. i don’t even know if this piece
of code is any good. it will probably serve to remind me of the
usage of certain functions etc at a later date. may be it will
scare somebody off and may be some kind stranger will correct my
mistakes and point me to enlightened realms. all this does is to
compute the column sums of a matrix. notice that we maintain our
distance from the for and while loops. i have been admonished
myriads of time for not using the standard library functions so i
have avoided them here. what can i say i simply love the lambda
functions over functors. although the compiler ultimately uses
functors behind the scenes but i love how clean and separated the
code looks.
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <cstdlib>
int main(){
// matrix
std::vector<std::vector<int> > a = {{0,0,0}, {0,0,0}, {0,0,0}};
// c++0x allows initialization lists
// randomly initialize using lambda expressions
std::for_each(a.begin(), a.end(), [](std::vector<int>& i){
std::generate(i.begin(), i.end(), [](){return rand()%10;});
});
// display using lamda expressions
std::for_each(a.begin(), a.end(), [](std::vector<int>& i){
std::copy(i.begin(), i.end(), std::ostream_iterator<int>(std::cout, "\t"));
std::cout << std::endl;
});
// zero vector
std::vector<int> zeros = {0,0,0};
// column sums
std::vector<int> csums = std::accumulate(a.begin(), a.end(), zeros,
[](std::vector<int>& i, std::vector<int>& j)->std::vector<int>{
std::transform(i.begin(), i.end(), j.begin(), i.begin(), std::plus<int>());
return i;
});
// display the column sums using ostream_iterators
std::copy(csums.begin(), csums.end(), std::ostream_iterator<int>(std::cout, "\t"));
return 0;
}
i now explain bits and parts of the mess
// randomly initialize
std::for_each(a.begin(), a.end(), [](std::vector<int>& i){
std::generate(i.begin(), i.end(), [](){return rand()%10;});
});
the above initializes the matrix a. since each element of a is itself a vector i use a lambda function that initializes the individual vectors. the lambda is as follows:
[](std::vector<int>& i){std::generate(i.begin(), i.end(), [](){return rand()%10;});}
the actual adding of columns is done using the std::accumulate() library function
// column sums
std::vector<int> csums = std::accumulate(a.begin(), a.end(), zeros,
[](std::vector<int>& i, std::vector<int>& j)->std::vector<int>{
std::transform(i.begin(), i.end(), j.begin(), i.begin(), std::plus<int>());
return i;
});
that uses the lamda
[](std::vector<int>& i, std::vector<int>& j)->std::vector<int>{
std::transform(i.begin(), i.end(), j.begin(), i.begin(), std::plus<int>());
return i;
}
Would just like to leave a tip about using std::array in place of std::vector – http://www.devx.com/cplus/Article/42114/1954
thank you for the tip