c++ - 使用迭代器修改二维向量
问题描述
我有一个使用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
解决方案
尝试更改矩阵值时,您正在迭代values ,而不是 references。相反,尝试
for (auto& x : m.iterator())
推荐阅读
- javascript - 如何使用 React 单击文档中的任意位置时关闭侧面板?
- azure - Microsoft 密码重置 - 包含重置后重定向 URI 的传递参数
- javascript - 在 JQuery 日期选择器上禁用 MySQL 数据库中的日期
- python - Flask API - 列出所有添加的资源
- ios - 可以在没有开发人员帐户的情况下使用推送通知吗?
- javascript - Jquery 从 if 语句中获取“this”
- python - 如何在 tkinter 中创建带有图像的按钮滑块?
- android - 我的其他应用未检测到模拟位置
- rest - 使用 .Net Identity Framework 保护 Rest API 内容
- css - HTML Canvas 在右下角对齐 DIV