[英]Can I use std::generate to get a vector of std::array<T, 2>?
使用std::generate
来获得T序列很容易。这里的简单示例代码:
std::vector<int> v(5);
std::generate(v.begin(), v.end(), [n = 0] () mutable { return n++; });
我可以使用std::generate
来获取std::vector<std::array<T,2>>
吗?
我的模板功能代码在这里:
#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;
}
我想将两个步骤合并为一个步骤,这样做方便吗?
你的lambda应该是
[n = -1, COLS = cols, ROWS = rows]() mutable {
++n;
return std::array<T, 2>{n % COLS, n / ROWS};
}
您只需要从您的lambda返回std::array<T, 2>
[n = -1, rows, cols]() mutable -> std::array<T, 2> { ++n; return { n % cols, n / rows }; }
如果要使行和列作为数组[0]和数组[1]动态生成,请尝试以下操作:
#include <iostream>
#include <vector>
#include <array>
#include <algorithm>
int main()
{
int rows = 5, cols = 3;
std::vector<std::array<int, 2>> vec(rows * cols);
std::generate(vec.begin(), vec.end(), [n = int(-1), cols]() mutable
{
++n;
return std::array<int, 2>{n % cols, n / cols};
});
// test
std::cout << "COL\tROW" << std::endl;
for (auto const &arr : vec)
std::cout << arr[0] << "\t" << arr[1] << std::endl;
return 0;
}
结果:
COL ROW
0 0
1 0
2 0
0 1
1 1
2 1
0 2
1 2
2 2
0 3
1 3
2 3
0 4
1 4
2 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.