C++:在指针集中查找
C++: find in set of pointers
下面的例子说明了我的问题:
#include <set>
class A {};
int main()
{
A a;
A * p = &a;
const A * cp = &a;
std::set<A*> s;
s.insert(p);
s.find(cp);
}
编译结束于:
a.cpp: In function ‘int main()’:
a.cpp:13:18: error: invalid conversion from ‘const A*’ to ‘std::set<A*>::key_type {aka A*}’ [-fpermissive]
s.find(cp);
^
In file included from /usr/include/c++/4.9.1/set:61:0,
from a.cpp:1:
/usr/include/c++/4.9.1/bits/stl_set.h:701:7: note: initializing argument 1 of ‘std::set<_Key, _Compare, _Alloc>::iterator std::set<_Key, _Compare, _Alloc>::find(const key_type&) [with _Key = A*; _Compare = std::less<A*>; _Alloc = std::allocator<A*>; std::set<_Key, _Compare, _Alloc>::iterator = std::_Rb_tree_const_iterator<A*>; std::set<_Key, _Compare, _Alloc>::key_type = A*]’
find(const key_type& __x)
我知道它为什么不编译,但有没有比s.find((A*)cp)
更丑陋、更残酷的解决方案?同时给出了set指针和const指针。
一个选项是将C++14透明运算符函子与异构查找一起使用:
std::set<A*, std::less<>> s;
s.find(cp);
不幸的是,libstdc++目前不支持异构查找,但它被标记为WIP。(它在clang/libc++中提供,并将在Visual Studio的下一个版本中提供。)如果没有它,你几乎只能使用const_cast
和cp
。
不幸的是,set
的查询方法没有在键类型上模板化(它们确实应该是),所以lower_bound
、equal_range
等没有帮助。
假设变量类型是不可协商的,那么您唯一的选择就是去掉指针的constness,或者reinterpret_cast
,将其设置为set<const A*>
。后者在某些方面让我感觉更好,但从技术上讲是不安全的。
抛开惊愕。使用const_cast
来做这件事,以明确这是演员阵容正在做的唯一事情。如果你喜欢的话,把它和find包装在一个免费函数中;如果一段代码是邪恶的,那么最好让邪恶的东西成为它所做的唯一的东西。
您可以将find与const_cast一起使用:
s.find(const_cast<A*>(cp));
相关文章:
- 正在查找文档以获得PS4平台的C++中的设备信息
- 在C++中查找文件
- 模板元程序查找相似的连续类型名称
- 在UNIX系统中使用DIR查找文件的字节大小
- 查找最接近的大于当前数字的数字的索引
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 查找后更改类变量
- 使用正则表达式regex_search在字符串中查找字符串
- 使用gcc从静态链接的文件中查找可选符号
- 如何从存储在std::映射中的std::集中删除元素
- 在C++中查找范围的长度
- 算法问题:查找从堆栈中弹出的所有序列
- 在Windows中查找扬声器输出的当前音量级别
- 如何在C++中使用X509证书模在令牌中查找私钥
- 使用.find函数在c++中查找字符和另一个字符之间的大小
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- 如何使用C++查找数据集中的局部最大值
- Binary_search 在 STL 集中查找 set 的成员函数?
- 在 c++ 集中查找相等的实例
- C++:在指针集中查找