通过迭代器检查某些内容是否已更改的方法
我已经实现了稀疏矩阵的列表列表,并且成功实现了迭代器和 const_iterator。
迭代器并不直接指向存储值的容器,而是创建一个结构体,命名为元素,如此定义:
template <typename T>
struct element{
int i,j; //Coordinates
T value;
};
但是迭代器有一个问题:当我使用它来编辑结构体中的值时,这甚至应该影响基质的内部结构。 我想将原始值存储在迭代器的其他私有属性中,然后将它们与存储到结构中的数据进行比较:如果有什么不同,我会调用矩阵的方法来编辑真正的内部结构。
我唯一想念的是:什么时候是在迭代器类中调用此方法的合适时机?
I have made a List of Lists implementation of a sparse matrix, and I've implemented iterator and const_iterator with success.
The iterator doesn't point directly to the container where the value is stored, but creates a struct, named element, so defined:
template <typename T>
struct element{
int i,j; //Coordinates
T value;
};
But there's one problem with the iterator: when I use it to edit the values in the struct, this should even affect the internal structure of the matrix.
I thought to store the original values in other private attributes of the iterator, then to compare them with the data stored into the struct: if something is different I'd call the methods of the matrix to edit the real internal structure.
The only thing I miss is: when is it the right moment to call this method inside iterator class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
简而言之,您应该在分配
*it
后立即调用此函数,其中it
是一个迭代器。我认为你没有正确的方法。 C++ 中的迭代器无法真正缓存更改,因为可能有其他迭代器指向容器中的同一位置。通过迭代器所做的更改应立即影响矩阵,并且矩阵中的更改应通过迭代器立即可见。这是一个测试用例:
因此,它应该直接访问矩阵,从那里读取值并存储值,而不是
element
存储用于矩阵的值的副本在那里(因此在需要存储时在稀疏矩阵中创建一个真实的条目)。另外,您的element
类应该可以转换为T
。The short answer, you should call this function as soon as
*it
is assigned to, whereit
is an iterator.I don't think you have the right approach. Iterators in C++ can't really cache changes, because there might be other iterators pointing at the same place in the container. Changes made via the iterator should affect the matrix immediately, and changes in the matrix should be visible via the iterator immediately. Here's a test case:
So rather than
element
storing a copy of the value intended for the matrix, it should directly access the matrix, reading the value from there and storing the value there (and hence creating a real entry in the sparse matrix when required to store). Also, yourelement
class should be convertible toT
.