开发者

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

开发者 https://www.devze.com 2022-12-12 05:53 出处:网络
Can I construct an std::map where the key type is a refe开发者_如何转开发rence type, e.g. Foo & and if not, why not?According to C++ Standard 23.1.2/7 key_type should be assignable. Reference type

Can I construct an std::map where the key type is a refe开发者_如何转开发rence type, e.g. Foo & and if not, why not?


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


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.


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.


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&

'

0

精彩评论

暂无评论...
验证码 换一张
取 消