c++ - 矩阵循环移位

标签 c++ stl matrix visual-c++-2005 shift

有谁知道对矩阵进行右循环移位的有效方法?顺便说一句,矩阵是二进制的,但求解非二进制矩阵的方法也可以。

现在,我正在考虑为矩阵的行实现一个循环数组,并在需要移位操作时更新每一行。

我正在考虑的另一种方法是实现一个指向由 vector 表示的(矩阵的)列的指针 vector ,并在发生移位操作时交换它们。

例如

1 2 3
4 5 6
7 8 9

右移

3 1 2
6 4 5
9 7 8

如果我还需要将矩阵向下移动,那么所有这些解决方案都会出现另一个问题。有效地实现这两个操作,完全超出了我的范围。

降档

9 7 8
3 1 2
6 4 5

最佳答案

也许是这样的,

class matrix {
    std::vector<bool> elements;
    int rows, cols, row_ofs, col_ofs;

    std::size_t index(int r, int c) {
        r = (r + row_ofs) % rows;
        c = (c + col_ofs) % cols;
        return std::size_t(r)*cols + c; // row major layout
    }
public:
    matrix() : rows(0), cols(0) {}
    matrix(int r, int c)
    : elements(std::size_t(r)*c), rows(r), cols(c) {}

    int num_rows() const { return rows; }
    int num_cols() const { return cols; }

    std::vector<bool>::reference operator()(int r, int c) {
        return elements.at(index(r,c));
    }

    bool operator()(int r, int c) const {
        return elements.at(index(r,c));
    }

    void rotate_left()  { col_ofs = (col_ofs+1     ) % cols; }
    void rotate_right() { col_ofs = (col_ofs+cols-1) % cols; }
    void rotate_up()    { row_ofs = (row_ofs+1     ) % rows; }
    void rotate_down()  { row_ofs = (row_ofs+rows-1) % rows; }
};

(未经测试)

编辑:这是一个替代方案:在内部使用 std::deque>。 ;-) 是的,它确实支持随机访问。双端队列不是列表。另外,您无需再为模运算而烦恼。

关于c++ - 矩阵循环移位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1478734/

相关文章:

c++ - 没有匹配的函数调用未解析的函数类型

c++ - 指定结构中数组元素的位大小

c++ - 已修复尝试在反转数组时修复损坏的代码

c++ - 从逆序C++访问 vector 时发生运行时错误

c++ - 知道 istream 是否以 C++ 中的字符串开头的惯用方法?

c# - 不确定在这种情况下如何正确使用 Matrix4.LookAt

algorithm - 矩阵链乘算法

python - 矩阵转置

c++ - constexpr Offsetof 带有指向成员数据的指针

c++ - 如何在 OpenCV 中获得扩展或收缩的轮廓?