自 C++14 以来,总是更喜欢 set<T,更少<>><T>?
Always prefer set<T, less<>> to set<T> since C++14?
#include <set>
#include <string>
#include <string_view>
using namespace std;
int main()
{
string_view key = "hello";
set<string> coll1;
coll1.find(key); // error
set<string, less<>> coll2;
coll2.find(key); // ok since C++14
}
那么,它应该是一个规则:
自 C++14 以来总是更喜欢set<T, less<>>
而不是set<T>
?
找到一个反例是微不足道的:
#include <set>
#include <string>
using namespace std;
struct converts_to_string {
operator string() const { return ""; }
};
int main()
{
converts_to_string key;
set<string> coll1;
coll1.find(key); // OK
set<string, less<>> coll2;
coll2.find(key); // error
}
使用associative_container<T, less<>>
时可能会有性能下降: 考虑类似
#include <iostream>
#include <set>
#include <string>
struct stupid_string
{
stupid_string(char const* s)
: s(s)
{ std::cout << "copyn"; }
stupid_string(char const* s, int) // silent
: s(s)
{}
friend bool operator<(stupid_string const& lhs, stupid_string const& rhs);
private:
std::string s;
};
bool operator<(stupid_string const& lhs, stupid_string const& rhs) {
return lhs.s < rhs.s;
}
int main() {
std::set<stupid_string, std::less<>> s;
s.emplace("hello", 0);
s.emplace("world", 0);
s.emplace("foobar", 0);
std::cout << "findn";
(void)s.find("test");
}
在这里,s.find
执行的算法中operator<
的应用会将字符文本隐式转换为stupid_string
。每次执行的比较都会发生这种情况!现场演示
我知道一个案例,在生产代码中发生了类似的事情,不符合 C++03 StdLib 的实现。
顺便说一下,这是选择加入通过less<>
进行异构查找的主要原因;请参阅 N3657:
斯蒂芬·T·拉瓦维(Stephan T. Lavavej)提出,保存的两个问题 现有行为和允许异构查找都可以是 通过让容器检测比较对象何时解决 接受异构参数,并且仅有条件地重载 具有模板版本的当前查找函数。
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 如何防止clang格式在流运算符调用之间添加换行符<<
- <<操作员在下面的行中工作
- EASTL矢量<向量<int>>连续的
- C - 创建矢量&lt; vector&lt; double&gt;&gt;矩阵具有分配而不是inizializ
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败
- C :对矢量进行排序&lt; struct&gt;(结构有2个整数)基于结构的整数之一
- 明确的专业化“ CheckIntmap&lt;&gt;”实例化
- 什么是模板&lt;&gt;inline bla bla
- 编辑C Qlist&lt; object*&gt; gt;QML代码和一些QML警告中的模型
- eigen :: llt&lt;eigen :: matrixxd&gt;具有不完整的类型
- 错误,包括&lt; ctype&gt;在原子上使用C 11
- std::vector<;uint8_t>;当C++11/14启用时,手动复制而不是调用memcpy
- 如何加入向量&lt; int&gt;到C 中的单个INT
- 是std :: set&lt; std :: future&gt;不可能存在
- 是numeric_limits&lt; int&gt; :: is_modulo从逻辑上矛盾
- opencv 2.4.7在iOS错误背景_segm.hpp #include&lt; list&gt;未找到
- 在修改列表后,std :: list&lt; t&gt; :: end()的值是否会更改
- ///<评论></评论>在Visual Studio中