mardi 30 janvier 2018

Can I use std::generate to get a vector of std::array

It's easy to use std::generate to get a sequence of T. Simple Example code here:

std::vector<int> v(5);
std::generate(v.begin(), v.end(), [n = 0] () mutable { return n++; });

Can I use std::generate to get std::vector<std::array<T,2>>?

My template function code here:

#include <algorithm>
#include <array>
#include <vector>
template<typename T>
std::vector<std::array<T, 2>> m(int rows, int cols) {
    std::vector<std::array<T, 2>> vec(rows*cols);
    // this is the x value I want to generate
    std::vector<T> x(rows*cols);
    std::generate(x.begin(), x.end(), 
                  [n = -1, COLS = cols]() mutable { ++n; return n % COLS;});
    // This is the y value I want to generate
    std::vector<T> y(rows*cols);
    std::generate(y.begin(), y.end(), 
         [n = -1, ROWS = rows]() mutable { ++n;  return floor(n / ROWS); });
    // Is it possible to combine the above steps into one step? 
    std::generate(vec.begin(), vec.end(), 
    [n = -1, COLS = cols, ROWS = rows]() mutable { ++n;  return .... });
    return vec;
}

I'd like to combine two steps into one step, is it any convenient way doing so?

Aucun commentaire:

Enregistrer un commentaire