[英]Sorting a vector of structs in C++
我有个问题。 声明说,比赛的结果是从标准输入中读取的,我必须将已解决问题的数量按降序显示在屏幕上。 这是我的代码。
#include <cstdio>
#include <vector>
#include <cstdlib>
using namespace std;
struct results
{
unsigned int id; //id of the team
unsigned int m; //number of solved problems
};
int comparare(const void * i, const void * j) //compare function for qsort()
{
return -( *(unsigned int*)i - *(unsigned int*)j );
}
int main()
{
unsigned int n;
vector<results> standings; //initializing an array of structs
scanf("%u", &n); //the size of the vector
for(unsigned int i=0; i<n; ++i)
{
scanf("%u%u", &standings[i].id, &standings[i].m); //reading the elements
standings.push_back(results());
}
qsort(standings, n, sizeof(results), comparare); //sorting the array
for(unsigned int i=0; i<n; ++i)
printf("%u %u\n", standings[i].id, standings[i].m); //print the sorted array
return 0;
}
当我要编译代码时,编译器会发现错误
无法将参数'1'的'std :: vector'转换为'void *'到'void qsort(void *,size_t,size_t,__compar_fn_t)'
在qsort(standings, n, sizeof(results), comparare);
我该怎么做才能解决这个问题?
如果您绝对必须在vector
上使用qsort
(并且您不应该也不应该),那么您必须像这样传递它:
qsort(standings.data(), standings.size(), sizeof(results), comparare);
vector::data
获取指向存储在vector
的数组的指针。 仅将指针传递给vector
本身将无济于事。
注意vector::data
需要C ++ 11; 如果没有可用的data
使用&vector[0]
。
但实际上, 只需使用std::sort
:
std::sort(standings.begin(), standings.end(), [](const results &lhs, const results &rhs) {return lhs.id < rhs.id;});
显然,lambda需要C ++ 11。 可以在早期的C ++版本中使用命名空间声明的结构。
您正在使用C构造,但是应该使用更多的C ++构造。 通常, std::sort
比qsort
快,并且其用法更加直观。 这是不使用C ++ 11即可重写它的方法。
#include <iostream>
#include <vector>
#include <algorithm>
struct results {
unsigned int id; //id of the team
unsigned int m; //number of solved problems
};
// I guess you're trying to sort on number of solved problems. If not, change `.m` to `.id`
bool comparare(const results lhs, const results rhs) {
return lhs.m > rhs.m;
}
int main() {
size_t n;
std::cout << "Enter number of results: " << std::endl;
std::cin >> n;
std::vector<results> standings(n); // Creates std::vector of results with n elements
// read in id and number of problems solved
for(size_t i=0; i < n; ++i) {
std::cin >> standings[i].id >> standings[i].m;
}
// sort the array
std::sort(standings.begin(), standings.end(), comparare);
// output the sorted array's id
for(size_t i = 0; i < standings.size(); ++i) {
std::cout << "In " << i+1 << " place: " << standings[i].id << " with " << standings[i].m << " problems solved." << std::endl;
}
return 0;
}
这是带有示例的ideone 。
你比较函数comparare
是不恰当的,如果该值可超过INT_MAX
。 例如,当将UINT_MAX - 0
作为int
返回时,比较UINT_MAX
和0
将导致溢出。 这是未定义的行为,在常见平台上实际上是负面的。
请使用以下比较功能:
//compare function for qsort()
int comparare(const void *i, const void *j) {
unsigned int ni = *(unsigned int*)i;
unsigned int nj = *(unsigned int*)j;
return (ni > nj) - (ni < nj);
}
它返回-1
, 0
或1
,如果*i
比分别比小于,等于或大于*j
。
在C ++中,还有其他更多惯用的方式对数组进行排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.