首页 > 解决方案 > 使用迭代器修改二维向量

问题描述

我有一个使用vector库的二维矩阵。我想更方便地迭代Matrix,所以我创建了一个MatrixIterator类。

矩阵.cpp

#include <vector>

template <class T>
class MatrixIterator;

template <class T>
class Matrix
{
    friend class MatrixIterator<T>;

private:
public:
    std::vector<std::vector<T>> m;
    unsigned rows_;
    unsigned cols_;

    Matrix<T>(unsigned rows, unsigned cols);

    MatrixIterator<T> iterator() const
    {
        return {*this};
    }

    MatrixIterator<T> begin() const
    {
        return {*this};
    }

    MatrixIterator<T> end() const
    {
        return {*this, rows_, 0};
    }
}


template <class T>
class MatrixIterator
{
private:
    Matrix<T> matrix_;
    unsigned row_;
    unsigned col_;

public:
    MatrixIterator<T>(Matrix<T> m) : matrix_(m), row_(0), col_(0) {};
    MatrixIterator<T>(Matrix<T> m, unsigned row, unsigned col) : matrix_(m), row_(row), col_(col) {};

    MatrixIterator<T> begin() const
    {
        return {matrix_};
    }

    MatrixIterator<T> end() const
    {
        return {matrix_, matrix_.rows_, 0};
    }

    void inc()
    {
        if(++col_ >= matrix_.cols_)
        {
            row_++;
            col_ = 0;
        }
    }

    MatrixIterator<T>& operator++()
    {
        inc();
        return *this;
    }

    MatrixIterator<T> operator++(int)
    {
        inc();
        return *this;
    }

    bool operator!=(const MatrixIterator<T> &rhs) const
    {
        return (row_ != rhs.row_) || (col_ != rhs.col_);
    }

    T& operator*()
    {
        return matrix_.m[row_][col_];
    }
};


template <class T>
Matrix<T>::Matrix(unsigned rows, unsigned cols)
    : rows_(rows), cols_(cols)
{

    m.resize(cols);
    for (unsigned i = 0; i < cols; i++)
    {
        m[i].resize(rows);
        fill(m[i].begin(), m[i].end(), T());
    }
}

在下面的代码中,当我尝试使用迭代器操作值时,它不会更改值。我尝试将值作为指针返回,operator*但它也不起作用。我没有看到任何错误。出了什么问题,我该如何解决?

主文件

#include "Matrix.cpp"
#include<iostream>
int main()
{
    Matrix<int> m = Matrix<int>{3,3};
    for(auto x: m.iterator())
        x = 10;
    for(auto x: m.iterator())
        std::cout << x << " ";
    // outputs 0 0 0 ~
}

编译g++ main.cpp -std=c++20 -g -o main && main

标签: c++multidimensional-arrayc++20

解决方案


尝试更改矩阵值时,您正在迭代values ,而不是 references。相反,尝试

for (auto& x : m.iterator())

推荐阅读