我可以构造密钥类型是引用类型(例如,引用类型)的std::map
。 Foo &
如果不是,为什么不呢?可以使用引用类型作为STL映射中的密钥类型
回答
根据C++标准23.1.2/7 key_type
应该是可赋值的。引用类型不是。
不,因为std :: map中的许多函数需要对keytype的引用,并且对引用的引用在C++中是非法的。
/A.B。
考虑operator[](const key_type & key)
。 如果key_type
是Foo &
那么什么是const key_type &
? 事情是它不起作用。你不能构造一个std :: map,其中键类型是引用类型。
指针作为关键类型的std ::地图是完全合法的
#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&
'
请记住,基于指针的排序是非确定性的,并可能随程序的每次调用而改变。 – 2009-11-25 15:16:40
更不用说比较键是否相等,因此这是比较查找时的指针地址值,而不是指针值的比较。具体来说,在这个例子中,如果有另外一个int e = 2,并且你查找了M [&e],你就不会得到你认为你正在寻找的东西。 – mmocny 2010-10-23 05:29:53
- 1. 使用类类型作为映射key_value
- 2. 使用映射将COM VARIANT类型映射到实际类型
- 3. 使用嵌套类型从类型到类型的AutoMapper映射
- 4. STL为相同的用户定义类型设置和映射
- 5. AutoMapper可以在值类型(枚举)和引用类型之间映射吗? (串)
- 6. SWIG类型映射为指针的STL地图一类
- 7. 作为第二种类型的自定义类的C++ STL映射
- 8. 在Typescript中使用Enum作为受限密钥类型
- 9. JNI - 映射UChar类型为
- 10. 序列化不同的密钥类型映射到JSON
- 11. 使用的.jar类型映射文件
- 12. 我可以使用JPA将对象类型映射到表吗?
- 13. 覆盖使用类型映射()
- 14. 使用NHibernate映射XML数据类型
- 15. 类型错误:使用替换映射
- 16. 使用NHibernate映射泛型类
- 17. 使用AutoMapper映射未知类型
- 18. 是可空类型的引用类型?
- 19. 使用泛型映射接口类型到类
- 20. Hiberate映射类型和保存类型
- 21. 将Oracle类型映射到Hibernate类型
- 22. Automapper:错误映射类型。映射类型:IEnumerable`1 - > IEnumerable`1
- 23. 使用类类型作为Java中的密钥DSL有效负载类型路由器
- 24. AutoMapper类型转换器映射可空类型不可空类型
- 25. 如何将类类型用作映射键和类的值列表作为映射值?
- 26. 地图的密钥类型
- 27. ehcache的密钥类型
- 28. 为什么使用枚举来映射hibernate中的类型表?
- 29. AutoMapper - 如何映射到嵌套类型的值 - 可以为null?
- 30. 如何引用java映射中的类型的对象?
+1这是一个很好的问题是很多人都不敢问。 – laura 2009-11-25 10:52:46
不是直接的,但'boost :: reference_wrapper'应该可以工作。它有一个隐式转换为'Foo&' –
MSalters
2009-11-26 10:11:06