我可以使用 std::generate 来获取 std::array<T, 2> 的向量吗?

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

本文关键字:std gt 向量 可以使 generate 获取 array lt 我可以      更新时间:2023-10-16
很容易

使用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