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

时间:2018-01-30 14:09:56

标签: c++ c++11 vector stl

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

我想将两个步骤合并为一步,这样做是否方便?

3 个答案:

答案 0 :(得分:4)

你的lambda应该是

[n = -1, COLS = cols, ROWS = rows]() mutable {
    ++n;
    return std::array<T, 2>{n % COLS, n / ROWS};
}

答案 1 :(得分:1)

您只需要从lambda中返回std::array<T, 2>

[n = -1, rows, cols]() mutable -> std::array<T, 2> { ++n; return { n % cols, n / rows }; }

答案 2 :(得分:1)

如果你想让row和cols动态生成为array [0]和array [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