Ada*_*dam 2 c++ iterator c++17
我有一个数据结构,它本质上是一个哈希表。出于缓存原因,键和值分开存储。我有一个迭代器,它遍历容器并在取消引用时返回键和值对。
但是,我在让迭代器像其他人一样运行时遇到了一些麻烦。特别是与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;
};
Run Code Online (Sandbox Code Playgroud)
这适用于 range-for 和显式取消引用迭代器
auto it = container.begin();
KeyValuePair pair = *it;
Run Code Online (Sandbox Code Playgroud)
但它不适用于“通过”迭代器,因为我没有 operator->
auto it = container.begin();
int& value = it->value;
Run Code Online (Sandbox Code Playgroud)
我不知道如何实现operator->这个迭代器。我的第一个想法是KeyValuePair在迭代器中粘贴 a并返回一个指向它的指针,但是没有诡计就无法重新设置引用。
比我更聪明的人有什么提示吗?
如果您不能从 返回指针operator->,则按值返回一个辅助类。使该类存储 aKeyValuePair并重载它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;
};
Run Code Online (Sandbox Code Playgroud)