繁体   English   中英

C ++ STL中SORT的自定义比较功能?

[英]Custom comparison function for SORT in C++ STL?

我在用

       typedef pair < long , pair <bool ,long > > t;
       vector <t> time ;

我需要使用std::sort()函数但使用一个自定义的比较函数对上述向量进行std::sort() 我写了一个版本,但是不能正常工作。 你能指出我的错误吗?

     bool comp ( const t &a , const t &b){

         if ( a.first < b.first)
             return a.first > b.first ;
         else if ( b.first < a.first )
             return b.first > a.first ;
         else if ( a.first == b.first )
         {
             if ( a.second.first == false && b.second.first == true)
                return a.first > b.first ;
             else if ( a.second.first == true && b.second.first == false)
                return b.first > a.first ;
             else
                return a.first > b.first ;
          }
      }


      inside main(){
         sort ( time.begin() ,time.end() ,comp) ;
      }

自定义案例:

排序前:向量时间

       10 1 1 
      100 0 1
      100 1 2
      200 0 2
      150 1 2
      500 0 2
      200 1 2
      300 0 2

排序后:

      10 1 1
      100 0 1
      100 1 2
      150 1 2
      200 0 2
      200 1 2
      300 0 2
      500 0 2

它应该是:

if ( a.first < b.first)
    return true
else if ( b.first < a.first )
    return false;
// etc.

在您的版本中,两种情况下均返回false。

您的比较功能未定义顺序。 实际上,似乎任何时候a.first != b.first返回true。

我不确定您要哪种自定义订单。 std :: pair的标准顺序将导致类似:

bool
comp( t const& a, t const& b )
{
    if ( a.first != b.first )
        return a.first < b.first;
    else if ( a.second.first != b.second.first )
        return a.second.first < b.second.first;
    else 
        return a.second.second < b.second.second;
}

实际上,它有点复杂,因为它使用的唯一比较运算符是< 但是,如果<!=都可用,并且行为正常,则结果与上述相同。

您可以轻松地采用这种方式以所需的任何顺序比较元素。 如果要反转元素之一的顺序,只需将<替换为>

最后,对于布尔值, false小于true

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM