[英]2d vector modify with iterator
我有一個使用vector
庫的二維矩陣。 而且我想更方便地迭代Matrix
,所以我創建了一個MatrixIterator
class。
矩陣.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())
您需要在迭代器 class 中存儲引用,而不是保存它的副本(迭代器只是數據的視圖)。
template <class T>
class MatrixIterator {
private:
Matrix<T>& matrix_;
unsigned row_;
unsigned col_;
public:
MatrixIterator<T>(Matrix<T>& m) : MatrixIterator<T>(m, 0, 0) {}
MatrixIterator<T>(Matrix<T>& m, unsigned row, unsigned col)
: matrix_(m), row_(row), col_(col) {}
};
而且您還需要為您的矩陣使用非常量begin
和end
,非常量版本迭代器可用於更改基礎值。 function iterator()
可以在此處刪除,因為在 c++ 代碼中並不常見。
MatrixIterator<T> begin() const { return {*this}; }
MatrixIterator<T> begin() { return {*this}; }
MatrixIterator<T> end() const { return {*this, rows_, 0}; }
MatrixIterator<T> end() { return {*this, rows_, 0}; }
要使用迭代器更改值,除了更改主 function 中的復制值之外,您還需要一個引用。 這里不需要顯式調用iterator
,編譯器會為你做。
int main() {
Matrix<int> m = Matrix<int>{3, 3};
for (auto& x : m) x = 10;
for (auto x : m) std::cout << x << " ";
return 0;
}
在線演示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.