我有一个本质上是哈希表的数据结构。出于缓存原因,键和值分开存储。我有一个遍历容器并在取消引用时返回键和值对的迭代器。
但是,我在让迭代器表现得像其他迭代器时遇到了一些麻烦。特别是 operator->
。这是我到目前为止所拥有的:
struct KeyValuePair
{
KeyValuePair(const int& key, int& value) : key(key), value(value) {}
const int& key;
int& value;
};
struct Iterator
{
KeyValuePair operator*() { return KeyValuePair(*keys, *values); }
// TODO: Implement this
//KeyValuePair* operator->() { return ... }
int* keys = nullptr;
int* values = nullptr;
};
这适用于 range-for 和显式取消引用迭代器
auto it = container.begin();
KeyValuePair pair = *it;
但它不适用于“通过”迭代器,因为我没有 operator->
auto it = container.begin();
int& value = it->value;
而且我不知道如何为这个迭代器实现 operator->
。我的第一个想法是在迭代器中插入一个 KeyValuePair
并返回一个指向它的指针,但是如果没有恶作剧就无法重新设置引用。
比我聪明的人有什么提示吗?
最佳答案
如果您不能从 operator->
返回一个指针,则按值返回一个辅助类。使该类存储 KeyValuePair
并重载其 operator->
以返回指向该对的指针。
我的回答使用了与 RedFog 相同的想法,但我尽量使代码不那么复杂。
struct Iterator
{
KeyValuePair operator*() const
{
return KeyValuePair(*keys, *values);
}
class ArrowHelper
{
KeyValuePair value
public:
ArrowHelper(KeyValuePair value) : value(value) {}
KeyValuePair *operator->() const
{
return &value;
}
};
ArrowHelper operator->() const
{
return **this;
}
int* keys = nullptr;
int* values = nullptr;
};
关于c++ - operator-> 用于返回临时值的迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64274156/