使用string_view进行地图查找
Use of string_view for map lookup
以下代码无法在最近的编译器(g++-5.3,clang++-3.7)上构建。
#include <map>
#include <functional>
#include <experimental/string_view>
void f()
{
using namespace std;
using namespace std::experimental;
map<string, int> m;
string s = "foo";
string_view sv(s);
m.find(sv);
}
叮当返回的错误:
error: no matching member function for call to 'find'
m.find(sv);
~~^~~~
但是find
不应该能够使用类似的类型吗?Cpp首选项提到了以下重载:
template< class K > iterator find( const K& x );
boost::string_ref
.
您需要显式指定透明比较器(如std::less<>
):
std::map<std::string, int, std::less<>> m;
// ~~~~~~~~~~^
std::map<K,V>
默认其比较器为std::less<K>
(即非透明比较器),并且自([associaciative.reqmts]/p13)以来:
成员函数模板
find
、count
、lower_bound
、upper_bound
和equal_range
不应参与重载解析,除非限定 idCompare::is_transparent
有效并表示类型 (14.8.2)。
模板成员函数find
不是可行的候选项。
关联容器的异构比较查找已添加到 c++14 中。最初的提案冒着破坏现有代码的风险。例如:
c.find(x);
在语义上等效于:
key_type key = x;
c.find(key);
特别是,x
和 key_type
之间的转换只发生一次,并且在实际调用之前。
异构查找取代了这种转换,有利于key
和x
之间的比较。这可能会导致现有代码的性能下降(由于每次比较前的额外转换)甚至中断编译(如果比较运算符是成员函数,则不会对左侧操作数应用转换):
#include <set>
#include <functional>
struct A
{
int i;
A(int i) : i(i) {}
};
bool operator<(const A& lhs, const A& rhs)
{
return lhs.i < rhs.i;
}
int main()
{
std::set<A, std::less<>> s{{1}, {2}, {3}, {4}};
s.find(5);
}
演示
为了解决这个问题,通过添加链接问题中所述的透明比较器的概念,使新行为选择加入。
相关文章:
- 在地图和列表之间查找标准容器
- 了解标准::地图::查找
- std::在地图上查找无法正常工作并循环访问地图的键和值
- 如何使用地图::在地图上查找
- 如何在给定任意数量的整数的情况下创建一个唯一键?并使用该键存储,然后从地图中查找
- 在地图键的矢量中查找多个字符串
- 如何在具有非常量指针键的地图中通过常量指针键查找
- 在STL地图中通过参考查找并返回
- 查找地图C 没有在地图中找到已经添加的密钥
- 按值在地图中查找 - 方法在速度方面的偏好
- 带地图的 GUI C++最短路径查找器
- 在给定键 (C++) 的地图向量内查找项目
- 在地图列表中查找
- STL 地图查找无法正常工作
- 使用在地图上查找<对,int>
- 如何在将多维 int 数组映射到 C++ 中的字符串时实现在地图上查找或计数
- 地图的查找功能得到错误的结果
- 使用string_view进行地图查找
- 在地图矢量内查找对
- C++11:如何获取C++14模板化地图::查找