c++ - operator-> 用于返回临时值的迭代器

标签 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;
};

这适用于 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/

相关文章:

c++ - 模板类返回元组或值,取决于参数包

C++ 范围-v3 : trying to chain together transforms

c++ - 我如何让 main 成为我类(class)的 friend ?

c++ - 我应该如何比较指针对(用于排序谓词)

c# - 如何使用 OpenCV 从图像中检测旋转对象?

c++ - Eigen::MatrixXd 到 flann::Matrix<double> 转换

c++ - "Out of bound iterator"为空集

c++ - STL迭代器包装器

c++ - 使用迭代器范围将单个元素附加到容器

c++ - 实际上对碎片内存进行碎片整理,就好像它在 C++ 中是连续的一样