如何解决operator->用于返回临时值的迭代器
我有一个本质上是哈希表的数据结构。出于缓存原因,键和值分别存储。我有一个遍历容器的迭代器,并在取消引用时返回键和值对。
但是,让迭代器表现得像其他人一样有点麻烦。特别是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;
};
,
迭代器有时会返回一个临时对象作为“引用”,但是operator->
通常需要一个左值来获取其指针。在这种情况下,为了让operator->
工作,我们应该提供指针的包装:(C ++ 11版本)
struct KeyValuePair
{
KeyValuePair(const int& key,int& value) : key(key),value(value) {}
const int& key;
int& value;
private:
template<typename T>
struct Helper{
T ref;
T* operator->(){ return std::addressof(ref); }
};
Helper<KeyValuePair> get(){ return Helper<KeyValuePair>{*this}; }
friend struct Iterator;
};
struct Iterator
{
KeyValuePair operator*() { return KeyValuePair(*keys,*values); }
auto operator->()->decltype((*(*this)).get()){
return (*(*this)).get();
}
int* keys = nullptr;
int* values = nullptr;
};
如果“引用”对象(KeyValuePair
)是可复制构造的,则它起作用。必须在Helper
的构造函数中进行复制,因为临时KeyValuePair
将在返回包装器之后被破坏。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。