【发布时间】:2012-04-24 01:21:46
【问题描述】:
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[5];
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;
#ifdef USEQSORT
qsort(pcount, structs_len, sizeof(port_count_t), struct_cmp_by_port_count);
#else
std::sort(pcount,(pcount+structs_len),cmp_by_port_count);
#endif
}
}
#ifdef USEQSORT
/* qsort struct comparision function compare port frequency*/
int struct_cmp_by_port_count(const void *a, const void *b)
{
port_count_t *ia = (port_count_t *)a;
port_count_t *ib = (port_count_t *)b;
return (ia->port_count - ib->port_count);
}
#else
/* qsort struct comparision function compare port frequency*/
int cmp_by_port_count(const port_count_t& a, const port_count_t& b)
{
return (a.port_count < b.port_count);
}
#endif
我有一个大的 std::map 结构,它将 port_count 映射到 port_number。我必须根据 port_count 找到最大的 5 个元素。(其中 key 是 port_number)。我上面给出了一个解析循环,它调用对大小为 5 的数组进行排序算法(qsort 或 std::sort)。这是实现这一目标的最有效方法吗?就排序函数的调用次数而言。是否有更好的方法来做到这一点,就计算效率?我还尝试了 qsort 和 std::sort ,它们的性能似乎都差不多。这是因为我正在排序的数组的大小太小而无法产生重大影响。我试图理解该算法在复杂性方面。任何想法将不胜感激。
【问题讨论】:
-
你不应该每次将元素添加到前 5 时都进行完整排序。由于数组中的 5 已经排序,你所要做的就是找到插入新元素的位置元素并将所有必要的元素向下移动 1 (当然丢弃最后一个元素)。您应该可以在
O(n)中执行此操作,这比任何排序方法都快。但是,由于数组只有 5 个元素,因此从中获得的任何收益都可能可以忽略不计。 -
为什么我的问题是-1