我将一个7x5矩阵展平为std :: vector,我想使用Eric Niebler的range-v3库查看列和行的视图。到目前为止,我设法(有改进的余地)对单行,单列和连接的行进行了查看。
请参阅:https://wandbox.org/permlink/8o4RgSucF3zSNuPN
std::vector<int> numbers = {
00, 01, 02, 03, 04,
10, 11, 12, 13, 14,
20, 21, 22, 23, 24,
30, 31, 32, 33, 34,
40, 41, 42, 43, 44,
50, 51, 52, 53, 54,
60, 61, 62, 63, 64,
};
const size_t n = 5;//number of columns
//Row_3 = {30, 31, 32, 33, 34}
auto Row_3 = numbers | GetRow(3, n);
std::cout << Row_3 << std::endl;
//Col_2 = {02, 12, 22, 32, 42, 52, 62}
auto Col_2 = numbers | GetColumn(2, n);
std::cout << Col_2 << std::endl;
//Row_2_3_4 = {{20, 21, 22, 23, 24},
// {30, 31, 32, 33, 34},
// {40, 41, 42, 43, 44}}
auto Rows_2_3_4 = numbers | GetConnectedRows(2, 4, n);
std::cout << Rows_2_3_4 << std::endl;
但是如何快速查看:
行列表:
auto a = numbers | GetRows({2,3,5}, n);
连接的列:
auto b = numbers | GetCols(2, 4, n);
列列表:
auto c = numbers | GetCols({1,2,4}, n);
行列表(“未排序”):
auto d = numbers | GetRows({5,2,3}, n);
列列表(“未排序”):
auto e = numbers | GetCols({4,1,2}, n);
?
答案 0 :(得分:6)
您可以仅将索引传送到适当的ranges::view::transform
。
包装在班上:
class Matrix
{
std::vector<int> data;
size_t col_count;
auto to_row(){ return [this](size_t i){ return data | ranges::view::drop(i * col_count) | ranges::view::take(col_count); }; };
auto to_col(){ return [this](size_t i){ return data | ranges::view::drop(i) | ranges::view::stride(col_count); }; };
public:
auto get_rows(size_t start, size_t end)
{ return ranges::view::ints(start, end) | ranges::view::transform(to_row()); }
auto get_rows(std::initialiser_list<size_t> indexes)
{ return indexes | ranges::view::transform(to_row()); }
auto get_cols(size_t start, size_t end)
{ return ranges::view::ints(start, end) | ranges::view::transform(to_col()); }
auto get_cols(std::initialiser_list<size_t> indexes)
{ return indexes | ranges::view::transform(to_col()); }
};
或作为管道视图
auto GetColumns(std::initialiser_list<size_t> indexes, size_t n)
{
return ranges::make_pipeable([=](auto &&rng) {
auto to_col = [&rng, n](size_t i){ return rng | GetCol(i, n); };
return indexes | ranges::view::transform(to_col);
});
}
auto GetRows(std::initialiser_list<size_t> indexes, size_t n)
{
return ranges::make_pipeable([=](auto &&rng) {
auto to_row = [&rng, n](size_t i){ return rng | GetRow(i, n); };
return indexes | ranges::view::transform(to_col);
});
}