【问题标题】:convert a pointer to a reverse vector iterator in STL在 STL 中将指针转换为反向向量迭代器
【发布时间】:2009-10-02 21:59:08
【问题描述】:

我有

sort(arr, arr+n, pred);

如何倒序排列?

【问题讨论】:

  • pred 是你写的谓词吗?

标签: c++ stl iterator


【解决方案1】:

似乎也有可能使用反向迭代器...除了使用反向谓词可能更容易,除非类型没有实现operator> :)

#include <iostream>
#include <algorithm>
#include <iterator>

int main()
{
    int arr[4] = { 3, 2, 5, 4 };
    std::sort(std::reverse_iterator<int*>(arr + 4), std::reverse_iterator<int*>(arr));
}

【讨论】:

    【解决方案2】:

    如果给您pred(即您无法进入其中以颠倒顺序),则类似于:

    std::sort(arr, arr+n, boost:bind<bool>(pred, _2, _1));
    

    【讨论】:

      【解决方案3】:

      您可以使用标准库中的greater,它会自动调用operator&gt; 来获取您想要排序的类型。

      #include <funcitonal>
      .....
      sort(arr, arr+n, greater<Type>()); // Type could be double for example
      

      【讨论】:

        【解决方案4】:

        否定pred的返回值。

        【讨论】:

        • 我认为您需要的不止这些。 Pred 需要是严格的弱排序,例如,像 = not >.
        • 大卫说得对,你需要反转操作数,而不是取反返回值。
        【解决方案5】:

        正如alrady 所说,您应该提供一个反向谓词。如果由于某些原因(例如纯粹的懒惰)不能,您总是可以先排序然后反转:

        sort(arr, arr+n, pred);
        reverse( arr, arr+n );
        

        这对计算机来说会做更多的工作,但它很清楚并且可以完成工作。如果您需要这种排序的速度性能,请使用反向谓词解决方案。

        【讨论】:

          【解决方案6】:

          我似乎很容易

          std::sort(myVec.rbegin(),myVec.rend());
          
          
          int main() 
          {
              typedef std::vector<int> vecType;
              vecType myVec;
              for(int a=0;a<20;a++)
              {
                  myVec.push_back((rand()%100));
              }
              std::copy(myVec.begin(), myVec.end(), std::ostream_iterator<int>(std::cout, "\n"));
              cout<<"\n---------------------------------------------------\n";
              std::sort(myVec.rbegin(),myVec.rend());
              std::copy(myVec.begin(), myVec.end(), std::ostream_iterator<int>(std::cout, "\n"));
              return 0;   
          }
          

          【讨论】:

            【解决方案7】:
            sort(arr, arr+n, std::not1(pred));
            

            见:http://www.cplusplus.com/reference/std/functional/not1/

            【讨论】:

            • 错误:pred(a,a) 应该返回 false,但 not1(pred(a,a)) 错误返回 true。这可能会导致sort() 挂起。
            猜你喜欢
            • 2020-11-06
            • 2016-09-17
            • 2011-01-03
            • 1970-01-01
            • 1970-01-01
            • 2010-10-19
            • 2023-04-04
            • 1970-01-01
            相关资源
            最近更新 更多