【发布时间】:2019-03-18 21:46:09
【问题描述】:
我有一个 Objects 列表,其中存储了一些 Data。一旦一个对象被添加到列表中,它将永远不会被删除。给定一些数据,我还想快速查找它来自哪个对象。
我想创建从数据到对象的映射,而不是遍历整个列表并检查每个对象。
#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());
}
为了节省空间,我在地图中使用了参考。对象和数据已经存储在列表中,我知道它们永远不会被删除。
但是,我在尝试编译此程序时遇到以下错误。
/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.
错误的主要部分似乎是:
错误:'operator[]' 的多个重载实例化为相同的签名
【问题讨论】:
-
看起来原始问题已得到解答,但您可以通过以下任一方法改进您的解决方案: A. 使用 std::unordered_map 而不是 std::map,查找是 O(1) 而不是O(lg(N)) 所以理论上会快得多。(你必须定义一个哈希函数)。或 B. 由于您要添加“bool operator
-
稍微偏离主题,但谷歌只能找到错误“地址实例化到相同签名的多个重载”的此链接,对于(我的情况)向量:Does C++ allow vector<const T>?(编号)@987654322 @(编号)