簡體   English   中英

使用 std::sort 計算交換

[英]Counting swaps using std::sort

是否有一種可移植的、開銷最小的方法來計算 C++ 中std::sort期間執行的交換操作的數量? 我想這樣做是因為我需要計算用於對列表進行排序的排列符號,並且我想知道是否有一種方法可以重用std::sort而不是編寫我自己的排序函數。

我試圖通過制作一個包裝器/自定義類型來重載 std::swap 來快速回答......然后遇到了一個事實,即不調用超小向量交換......按照評論中的鏈接嘗試2為 move_constructor 添加了一個計數器。

我不能說這是一個最小開銷的解決方案,如果您需要交換操作的確切數量,您最好編寫自己的排序函數。

#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;

}

給我

after sort1: swap count:0 move count: 9
after sort2: swap count:1806 move count: 999

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM