我想知道为什么std::map并std::set使用std::less默认仿函数来比较键.为什么不使用类似于strcmp的仿函数?就像是:
template <typename T> struct compare
{
// Return less than 0 if lhs < rhs
// Return 0 if lhs == rhs
// Return greater than 0 if lhs > rhs
int operator()(T const& lhs, T const& rhs)
{
return (lhs-rhs);
}
}
Run Code Online (Sandbox Code Playgroud)
说一个map有两个对象,用键key1和key2.现在我们要插入另一个带键的对象key3.
使用时std::less,该insert功能需要先std::less::operator()用key1和调用key3.假设std::less::operator()(key1, key3)返回false.它必须std::less::operator()再次通过键切换std::less::operator()(key3, key1),以决定是否key1等于 …
定义<运算符后,您就可以估计其余关系运算符的行为方式。我正在尝试为我的课程实现一种方法。
我想要的是仅定义<和其余的运算符隐式默认。到目前为止我所得到的是这个设计,我将在下面进一步详细说明:
template<typename T>
struct relational
{
friend bool operator> (T const &lhs, T const &rhs) { return rhs < lhs; }
friend bool operator==(T const &lhs, T const &rhs) { return !(lhs < rhs || lhs > rhs); }
friend bool operator!=(T const &lhs, T const &rhs) { return !(rhs == lhs); }
friend bool operator<=(T const &lhs, T const &rhs) { return !(rhs < lhs); }
friend bool operator>=(T const &lhs, T const &rhs) …Run Code Online (Sandbox Code Playgroud) 我必须在sort()函数中实现第三个参数cmp,以便按降序排序整数数组 .
问题是这个定义不能正常工作,
bool cmp (int a, int b)
{
if(a<b)
return false;
else
return true;
}
Run Code Online (Sandbox Code Playgroud)
但是,这样做
bool cmp (int a, int b)
{
if(a<=b)
return false;
else
return true;
}
Run Code Online (Sandbox Code Playgroud)
在main()函数中,我使用
sort(Arr,Arr+n,cmp);
Run Code Online (Sandbox Code Playgroud)
请注意,我声称第一个代码无法正常工作,因为当我使用第二个时,我接受了Codechef问题的解决方案,而不是第一个.