相关疑难解决方法(0)

为什么使用std :: less作为比较std :: map和std :: set中的键的默认函子?

我想知道为什么std::mapstd::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有两个对象,用键key1key2.现在我们要插入另一个带键的对象key3.

使用时std::less,该insert功能需要先std::less::operator()key1和调用key3.假设std::less::operator()(key1, key3)返回false.它必须std::less::operator()再次通过键切换std::less::operator()(key3, key1),以决定是否key1等于 …

c++ stdmap stdset

35
推荐指数
2
解决办法
2140
查看次数

C++ 关系运算符生成器

定义<运算符后,您就可以估计其余关系运算符的行为方式。我正在尝试为我的课程实现一种方法。

我想要的是仅定义<和其余的运算符隐式默认。到目前为止我所得到的是这个设计,我将在下面进一步详细说明:

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)

c++ templates

2
推荐指数
1
解决办法
1561
查看次数

在C++中使用STL的比较函数中的"<="符号而不是"<"符号有什么区别?

我必须在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问题的解决方案,而不是第一个.

c++ stl

0
推荐指数
1
解决办法
114
查看次数

标签 统计

c++ ×3

stdmap ×1

stdset ×1

stl ×1

templates ×1