Подтвердить что ты не робот

Может ли ссылочный тип использоваться в качестве типа ключа в STL-карте

Могу ли я построить std::map, где тип ключа является ссылочным типом, например. Foo &, а если нет, почему бы и нет?

4b9b3361

Ответ 1

В соответствии с С++ Стандарт 23.1.2/7 key_type должен быть назначен. Тип ссылки отсутствует.

Ответ 2

Нет, потому что многие из функций в std:: map ссылаются на ключ и ссылки на ссылки являются незаконными в С++.

/A.B.

Ответ 3

Рассмотрим operator[](const key_type & key). Если key_type - Foo &, то что такое const key_type &? Дело в том, что оно не работает. Вы не можете построить std:: map, где тип ключа является ссылочным типом.

Ответ 4

Указатель как ключевой тип для std:: map вполне легален

#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;
}

Инициализированные ссылки не могут быть ключами:

#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&