c++ - Generate matrix with std::generate -
using reference. behavior of std::generate should equivalent to:
template <class forwarditerator, class generator> void generate ( forwarditerator first, forwarditerator last, generator gen ) { while (first != last) { *first = gen(); ++first; } }
but when try fill matrix 0-99 numbers. instead 10 rows of 0-9. why that?
std::vector< std::vector<int> > m; #ifdef generate struct generator{ int seq; generator():seq(0){}; int operator()(){return seq++;}; } generator; #elif defined for_each int = 0; auto increment = [&i](int &a){a = i++;}; #endif int x = 10, y = 10; m.resize(x); for(auto &v : m) { v.resize(y); #ifdef generate generate(begin(v), end(v), generator); #elif defined for_each for_each(begin(v),end(v), increment); #endif }
you may use std::ref prevent copying of generator object:
generate(begin(v), end(v), std::ref(generator));
Comments
Post a Comment