[英]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.