Can a reference type be used as the key type in an STL map

拟墨画扇 提交于 2019-12-06 17:01:21

问题


Can I construct an std::map where the key type is a reference type, e.g. Foo & and if not, why not?


回答1:


According to C++ Standard 23.1.2/7 key_type should be assignable. Reference type is not.




回答2:


No, because many of the functions in std::map takes a reference to the keytype and references to references are illegal in C++.

/A.B.




回答3:


Consider the operator[](const key_type & key). If key_type is Foo & then what is const key_type &? The thing is that it does not work. You can not construct an std::map where the key type is a reference type.




回答4:


Pointer as a key-type for std::map is perfectly legal

#include <iostream>
#include <cstdlib>
#include <map>

using namespace std;


int main()
{
int a = 2;
int b = 3;
int * c =  &a;
int * d =  &b;
map<int *, int> M;

M[c]=356;
M[d]=78;
return 0;
}

Initialised references cant be keys:

#include <iostream>
#include <cstdlib>
#include <map>

using namespace std;


int main()
{
int a = 2;
int b = 3;
int & c =  a;
int & d =  b;
map<int &, int> M;

M[c]=356;
M[d]=78;
return 0;
}
In file included from /usr/include/c++/4.4/map:60,
                 from test.cpp:3:
/usr/include/c++/4.4/bits/stl_tree.h: In instantiation of 'std::_Rb_tree<int&, std::pair<int&, int>, std::_Select1st<std::pair<int&, int> >, std::less<int&>, std::allocator<std::pair<int&, int> > >':
/usr/include/c++/4.4/bits/stl_map.h:128:   instantiated from 'std::map<int&, int, std::less<int&>, std::allocator<std::pair<int&, int> > >'
test.cpp:14:   instantiated from here
/usr/include/c++/4.4/bits/stl_tree.h:1407: error: forming pointer to reference type 'int&

'



来源:https://stackoverflow.com/questions/1796046/can-a-reference-type-be-used-as-the-key-type-in-an-stl-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!