相关疑难解决方法(0)

如何在现代C++中实现经典排序算法?

std::sort算法(及其同类std::partial_sortstd::nth_element从C++标准库)是在大多数实现的更基本的排序算法复杂和混合合并,如选择排序,插入排序,快速排序,归并排序,或堆排序.

这里和姐妹网站上有很多问题,例如https://codereview.stackexchange.com/,与错误,复杂性以及这些经典排序算法的实现的其他方面有关.大多数提供的实现包括原始循环,使用索引操作和具体类型,并且在正确性和效率方面分析通常是非常重要的.

:如何使用现代C++实现上述经典排序算法?

  • 没有原始循环,但结合了标准库的算法构建块<algorithm>
  • 迭代器接口模板的使用,而不是索引操作和具体类型
  • C++ 14风格,包括完整的标准库,以及语法降噪器,如auto模板别名,透明比较器和多态lambda.

备注:

  • 有关排序算法实现的进一步参考,请参阅Wikipedia,Rosetta Codehttp://www.sorting-algorithms.com/
  • 根据Sean Parent的惯例(幻灯片39),原始循环for比使用运算符的两个函数的组合更长.所以f(g(x));f(x); g(x);f(x) + g(x);不生循环,也不是在环路selection_sortinsertion_sort下方.
  • 我遵循Scott Meyers的术语来表示当前的C++ 1y已经作为C++ 14,并且将C++ 98和C++ 03都表示为C++ 98,所以不要因此而激怒我.
  • 正如@Mehrdad的评论中所建议的那样,我在答案的最后提供了四个实现作为实例:C++ 14,C++ 11,C++ 98和Boost and C++ 98.
  • 答案本身仅以C++ 14的形式呈现.在相关的地方,我表示各种语言版本不同的语法和库差异.

c++ sorting algorithm c++-faq c++14

322
推荐指数
2
解决办法
3万
查看次数

使用std :: greater

我对std :: greater的使用感到好奇。与结合使用时sort,它将以降序输出数字。但是,当与一起使用时priority_queue,数字将按升序输出。为什么这样?

例:

#include <iostream>     // std::cout
#include <functional>   // std::greater
#include <algorithm>    // std::sort
#include <queue>        // std::priority_queue

int main () {
  int numbers[]={20,40,50,10,30};
  std::priority_queue<int, std::vector<int>, std::greater<int>> pq (numbers, numbers+5);
  std::sort(numbers, numbers + 5, std::greater<int>());
  while(!pq.empty()){
      std:: cout << pq.top() << ' ';
      pq.pop();
  }
  std::cout << '\n';  
  for (int i=0; i<5; i++)
    std::cout << numbers[i] << ' ';
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

上面的代码输出为:

10 20 30 40 50 50 40 30 20 …

c++ priority-queue

4
推荐指数
1
解决办法
898
查看次数

为什么STL中的priority_queue不遵循严格的弱排序?

我一直在玩STL容器和它们支持的比较函数/仿函数,但是我发现priority_queue不遵循通常的严格弱序,我试图理解可能是什么原因但不能弄明白,任何指针会有所帮助.

它在本博客中还提到priority_queue不遵循严格的弱排序.在此输入链接描述

#include "STL.h"
#include "queue"
#include "vector"
#include "iostream"
#include "functional"
using namespace std;

typedef bool(*func)(const int& val1 , const int& val2);

bool strict_weak_order_function(const int& val1 , const int& val2){
    return val1 > val2;
}

bool comparer_function(const int& val1 , const int& val2){
    return !strict_weak_order_function(val1 , val2);
}

struct Compaper_functor{
    bool operator()(const int& val1 , const int& val2){
        return !strict_weak_order_function(val1 , val2);
    }
};


void runPriorityQueue(void){
    //priority_queue<int , vector<int> , func > pq(comparer_function);
    priority_queue<int , vector<int> , Compaper_functor …
Run Code Online (Sandbox Code Playgroud)

c++ stl priority-queue strict-weak-ordering

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