我可以使用 std::generate 来获取 std::array<T, 2> 的向量吗?
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 << "COLtROW" << 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
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从持续时间构造std::chrono::system_clock::time_point
- std::具有相同基类的类的变体
- std::向量与传递值的动态数组
- 使用std::vector的OpenCL矩阵乘法
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- std::condition_variable::wait()如何评估给定的谓词
- 如何获取std::result_of函数的返回类型
- std::原子加载和存储都需要吗
- 将对象移动到std::shared_ptr
- std::vector<;uint8_t>;当C++11/14启用时,手动复制而不是调用memcpy
- 是std :: set&lt; std :: future&gt;不可能存在
- 在修改列表后,std :: list&lt; t&gt; :: end()的值是否会更改
- 使用 std::vector<boost::shared_ptr<Base_Class>> 或 boost::p tr_vector 的性能注意事项是什么<Base>
- std::map<std::set, double> AND std:<long>map< std::p air<long, long>, double>
- 如何获取std::vector<DMatch>