【问题标题】:Comparing qsort with std::sort比较 qsort 与 std::sort
【发布时间】:2012-04-23 06:47:41
【问题描述】:

I am referring you to a previous link that compares the performance of qsort vs stdsort.

我编写了一个填充大std::map 的 C 程序,我想对数组进行排序。我目前使用的是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 函数正在正确地对数组进行排序。我想比较qsortstd::sort 的性能,但是调用std::sort 会出现编译错误

没有匹配函数调用‘sort(port_count_t [10], long unsigned int)’

我想比较std::sortqsort 算法的性能。我该怎么做?

【问题讨论】:

  • 如果您认为您的问题已得到解答,请接受相应的答案。

标签: c++ dictionary std stdmap qsort


【解决方案1】:

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

【讨论】:

  • +1。最后一部分很重要; std::sort 对比较器使用不同的约定。
【解决方案2】:

尝试调用:

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

std::sort 将开始和结束迭代器作为参数。因此,为了对数组进行排序,您需要传递一个指向数组开头的指针和一个指向数组结尾之后的一个元素的指针(始终为 array_pointer + array_size)。

【讨论】:

    猜你喜欢
    • 2011-06-10
    • 1970-01-01
    • 1970-01-01
    • 2017-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-03
    • 2022-01-05
    相关资源
    最近更新 更多