2012-04-23 86 views
0

I am referring you to a previous link that compares the performance of qsort vs stdsort比較qsort和std :: sort

我寫了一個C程序,填充一個大的std::map,我想排序數組。我目前使用qsort

typedef std::map<uint16_t, uint32_t> TSrcMap; 
TPSrcMap sp; 
TSrcMap::iterator its; 
/*Code to populate the array_start.*/ 

/*Code to populate the array_end.*/ 

typedef struct port_count 
{ 
     uint32_t port_number; 
     uint32_t port_count; 
}port_count_t; 

port_count_t pcount[10]; 
memset(pcount,0,sizeof(pcount)); 
size_t structs_len = sizeof(pcount)/sizeof(port_count_t); 
for(its = stcp.begin(); its != stcp.end();its++) 
{ 
     if(pcount[smallest_index].port_count < (*its).second) 
     { 
      pcount[smallest_index].port_count = (*its).second; 
      pcount[smallest_index].port_number = (*its).first; 
      /*qsort(pcount, structs_len, sizeof(port_count_t), struct_cmp_by_port_count);*/ 
      std::sort(pcount,sizeof(port_count_t)); 
     } 
} 

qsort函數正確地對數組進行排序。我想的qsort性能與std::sort但呼叫std::sort通話是給編譯錯誤

呼叫沒有匹配功能‘sort(port_count_t [10], long unsigned int)’

比較,我想的std::sort性能與qsort比較算法。我怎麼做?

+0

如果您認爲您的問題得到解答,請接受相應的答案。 – 2012-04-23 16:02:56

回答

6

std::sort()簽名是:

template <class RandomAccessIterator, class StrictWeakOrdering> 
void sort(RandomAccessIterator first, RandomAccessIterator last, 
      StrictWeakOrdering comp); 

所以它需要兩個迭代比較,而不是一個指針和一個長度。要解決你的代碼,調用

std::sort(pcount, pcount+structs_len, cmp_port_count); 

假設cmp_port_count是你比較函數引用其採用兩個port_count_t對象並返回true當第一個參數是第二個參數之前訂購,false否則。

+2

+1。最後一部分很重要; 'std :: sort'對比較器使用不同的約定。 – MSalters 2012-04-23 08:56:27

0

嘗試調用:

std::sort(pcount,pcount + 10); 

的std ::排序需要作爲參數的開始和結束迭代器。所以爲了對數組進行排序,你需要傳遞一個指向數組開頭的指針和一個指向數組結尾之後的一個元素的指針(它始終是array_pointer + array_size)。