gpt4 book ai didi

c++ - 'operator[]' 的多个重载实例化为相同的签名

转载 作者:搜寻专家 更新时间:2023-10-31 01:26:31 28 4
gpt4 key购买 nike

我有一个存储一些数据对象列表。一旦一个对象被添加到列表中,它就永远不会被删除。给定一些数据,我也想快速查找它来自哪个对象。

与其遍历整个列表并检查每个对象,不如创建一个从数据到对象的映射。

#include <vector>
#include <map>

class Data {/*Stuff here*/};

struct Object {
Data d;
Object(Data d) : d(d) {}
};

class ObjectStorage {
std::vector<Object> objects;
std::map<Data&, Object&> reverse_lookup;

public:
void add_object(Data d) {
objects.emplace_back(d);

auto &obj = objects.back();
reverse_lookup.emplace(obj.d, obj);
}
};

int main() {
ObjectStorage S;
S.add_object(Data());
}

为了节省空间,我在 map 中使用了引用资料。对象和数据已存储在列表中,我知道它们永远不会被删除。

但是,在尝试编译该程序时出现以下错误。

/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/map:1024:18: error: multiple overloads of 'operator[]' instantiate to the same signature 'std::__1::map<Data &, Object &, std::__1::less<Data &>, std::__1::allocator<std::__1::pair<Data &, Object &> > >::mapped_type &(std::__1::map<Data &, Object &,
std::__1::less<Data &>, std::__1::allocator<std::__1::pair<Data &, Object &> > >::key_type &)'
mapped_type& operator[](key_type&& __k);
^
test.cpp:13:27: note: in instantiation of template class 'std::__1::map<Data &, Object &, std::__1::less<Data &>, std::__1::allocator<std::__1::pair<Data &, Object &> > >' requested here
std::map<Data&, Object&> reverse_lookup;
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/map:1022:18: note: previous declaration is here
mapped_type& operator[](const key_type& __k);
^
1 error generated.

错误的主要部分似乎是:

error: multiple overloads of 'operator[]' instantiate to the same signature

最佳答案

错误源于在 std::map 中使用引用.见问题"Why Can't I store references in a std::map in C++?"有关原因的更多信息。

如果不是太贵,改reverse_lookup通过

映射到存储拷贝
std::map<Data, Object> reverse_lookup;

并为 bool operator<(const Data& lhs, const Data& rhs) 添加定义允许 Data用作 key 将解决问题。

如果复制DataObject太昂贵了,可以使用指针映射代替引用。但是,请注意指向数据的存储方式。在这种情况下,如果 objects vector 增长超过其内部容量并调整大小,所有指针都将变为无效。使用类似 std::list 的东西不会在内存中移动数据应该可以防止该问题。感谢Christophe感谢您在评论中指出这一点。

关于c++ - 'operator[]' 的多个重载实例化为相同的签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55230481/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com