I have a list of Object
s that store some Data
. Once an object is added to the list it will never be removed. Given some data, I would also like to quickly look up which object it came from.
Rather than loop over the entire list and check each object I would like to create a map from data to objects.
#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());
}
To save space I used references in the map. The objects and data are already stored in the list and I know they will never be removed.
However, I am getting the following error when trying to compile this program.
/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.
The main portion of the error seems to be:
error: multiple overloads of 'operator[]' instantiate to the same signature