Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用std::sort计算掉期 是否有一个可移植的、最小开销的方法来计算在 STD中执行的交换操作的数量:C++中的排序< /COD>?我想这样做是因为我需要计算用于排序列表的排列的符号,我想知道是否有一种方法可以重复使用std::sort,而不是编写自己的排序函数。_C++_Sorting - Fatal编程技术网

使用std::sort计算掉期 是否有一个可移植的、最小开销的方法来计算在 STD中执行的交换操作的数量:C++中的排序< /COD>?我想这样做是因为我需要计算用于排序列表的排列的符号,我想知道是否有一种方法可以重复使用std::sort,而不是编写自己的排序函数。

使用std::sort计算掉期 是否有一个可移植的、最小开销的方法来计算在 STD中执行的交换操作的数量:C++中的排序< /COD>?我想这样做是因为我需要计算用于排序列表的排列的符号,我想知道是否有一种方法可以重复使用std::sort,而不是编写自己的排序函数。,c++,sorting,C++,Sorting,我试图通过制作一个包装器/自定义类型来重载std::swap…来快速回答这个问题,然后在注释中的链接之后,遇到了一个事实,即对于超小向量,swap不被调用 因此,尝试2为move_构造函数添加了一个计数器 我不能说这是一个开销最小的解决方案,如果您需要交换操作的确切数量,您最好编写自己的排序函数 #include <iostream> #include <vector> #include <algorithm> #include <random>

我试图通过制作一个包装器/自定义类型来重载std::swap…来快速回答这个问题,然后在注释中的链接之后,遇到了一个事实,即对于超小向量,swap不被调用 因此,尝试2为move_构造函数添加了一个计数器

我不能说这是一个开销最小的解决方案,如果您需要交换操作的确切数量,您最好编写自己的排序函数

#include <iostream>
#include <vector>
#include <algorithm>
#include <random>

struct A{
  static int swap_count;
  static int move_constructor_count;
  int a;
  A(int _a): a(_a) {}
  bool operator<(const A& other) const{
    return this->a < other.a;
  }
  A(const A&other): a(other.a) {move_constructor_count++;}
};
int A::swap_count = 0;
int A::move_constructor_count = 0;

namespace std{
    template<>
    void swap(A& lhs, A& rhs) {
       A::swap_count++;
       std::swap(lhs.a, rhs.a);
    }
}


int main() {
  std::default_random_engine gen;
  std::uniform_int_distribution<int> dis(1,100);

  std::vector<A> test;
  for(int _=0;_<10;_++) test.emplace_back(dis(gen)); //fill a vector randomly

  A::move_constructor_count = 0; // emplace calls move constructor
  std::sort(test.begin(), test.end());
  std::cout << "after sort1: swap count:" << A::swap_count << " move count: " << A::move_constructor_count << std::endl;


  // arbitrary way to fill a large test vector
  std::vector<A> test2;
  for(int _=0;_<1000;_++) test2.emplace_back(dis(gen)); //fill a vector randomly
    
  A::move_constructor_count = 0;
  A::swap_count = 0;
  std::sort(test2.begin(), test2.end());
  std::cout << "after sort2: swap count:" << A::swap_count << " move count: " << A::move_constructor_count << std::endl;

}

这回答了你的问题吗@幼珍我不认为是这样的,但是我对C++是相当陌生的,不知道是否还有其他方法来实现这个“SWAP-CONTIN”。不幸的是,
std::swap
要求类型是可移动构造的。否则,您可以编写一个简单地拒绝任何移动欺骗的包装器。您可以计算自定义类型发生的复制/移动构造的数量。感谢您对此进行了破解,我最终编写了自己的堆排序,并只计算了交换。我考虑的另一件事是将数组转换为成对数组
(a[I],I)
,然后进行排序,这将在第二个因子中使用排列。但是你需要更多的代码来寻找和计算周期。。。
after sort1: swap count:0 move count: 9
after sort2: swap count:1806 move count: 999