gpt4 book ai didi

c++ - 在 C++ 中 reshape 2D vector

转载 作者:行者123 更新时间:2023-11-30 05:13:16 25 4
gpt4 key购买 nike

我想实现一个函数,它喜欢二维 vector (矩阵)的输入,包含它的原点元素,并根据输入的列数和行数返回一个 reshape 版本。重构后的矩阵需要按照与原矩阵相同的行遍历顺序填充原始矩阵的所有元素。

我完成了以下代码:

vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
int r_old = nums.size();
int c_old = nums[0].size();


if(r*c != r_old*c_old) return nums;

vector<vector<int>> new_nums;
new_nums.resize(r);

// get the new matrix proper size
for (int i =0; i< r; i++){
new_nums[i].resize(c);
}

int c_curr =0;
int r_curr =0;

// assign element
for (int i = 0; i < r_old; i ++){
for (int j =0; j < c_old; j++){

if(c_curr == c){
r_curr++;
c_curr =0;
}
new_nums[r_curr][c_curr] = nums[i][j];
c_curr++;
}
}
return new_nums;
}

但是,我觉得一定有更好的方法来做到这一点。我搜索了 stackoverflow,发现了几个问题

How can I resize a 2D C++ vector?

How can I resize a 2D vector of objects given the width and height?

但是,这些答案都“重置”了当前矩阵,这不是我想要的。所以我的问题是,是否有一种更快的方法可以通过将二维 vector 的元素重新排列成所需的新形状来从二维 vector 生成二维 vector ?

最佳答案

决定继续关注我的评论。这个答案相当深入 X-Y 领域,但它应该大大简化事情

#include <iostream>
#include <iomanip>
#include <vector>
#include <exception>

// wrapping class for 2D matrixes
class Matrix
{
private:
size_t rows, columns; // large, unsigned datatype. Don't want negative
// indices, so why allow them?
std::vector<int> matrix; // 1D vector. Simple and easy to handle.
// also often much faster than vector of vectors
// due to improved spatial locality helping
// predictability of data access
public:
// catchable exception should user request impossible dimension transformation
class BadDimsException: public std::exception
{
public:
const char* what() const noexcept
{
return "Invalid dimensions specified";
}
};

// build zero-filled Matrix
Matrix(size_t numrows, size_t numcols) :
rows(numrows), columns(numcols), matrix(rows * columns)
{
}

// build Matrix based on another Matrix with convertable dimensions
// All of the heavy lifting is performed in the member initializer list
// by simply copying data store of source Matrix
// if matrix cannot be transformed, the thrown exception leaves user with
// nothing to work with and no chance of trying to continue with an un-
// transformed matrix
Matrix(size_t numrows, size_t numcols, const Matrix & source) :
rows(numrows), columns(numcols), matrix(source.matrix)
{
if (rows * columns != source.rows * source.columns)
{ // Bad dimensions. Blow up.
throw BadDimsException();
}
}

// 2D to 1D mapping accessor
int & operator()(size_t row, size_t column)
{
// check bounds here
return matrix[row * columns + column];
}

// 2D to 1D mapping accessor for constant Matrix
int operator()(size_t row, size_t column) const
{
// check bounds here
return matrix[row * columns + column];
}

// dimension accessors
size_t getRows() const
{
return rows;
}
size_t getColumns() const
{
return columns;
}
};


// stream formatter
std::ostream & operator<<(std::ostream & out, const Matrix & mat)
{
for (size_t row = 0; row < mat.getRows(); ++row)
{
for (size_t col = 0; col < mat.getColumns(); ++col)
{
std::cout << std::setw(5) << mat(row, col);
}
std::cout << '\n';
}
return out;
}

并测试/演示用法:

int main()
{
Matrix one(2, 6); // make 2x6 matrix
int count = 0;

// set inputs to make errors really stand out
for (size_t row = 0; row < one.getRows(); ++row)
{
for (size_t col = 0; col < one.getColumns(); ++col)
{
one(row, col) = count++;
}
}

// print initial matrix
std::cout << one << '\n';

// make reshaped matrix
Matrix two(3,4, one);

//print reshaped Matrix
std::cout << two << '\n';
try
{
// make invalid reshaped matrix
Matrix three(3, 3, one);

// This should never print
std::cout << three << '\n';
}
catch (const Matrix::BadDimsException & bde)
{
// Yay! Caught error!
std::cout << bde.what() << '\n';
}
}

关于c++ - 在 C++ 中 reshape 2D vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44034503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com