c++ - 在 C++ 中对结构 vector 进行排序

标签 c++ struct qsort

我有一个问题。声明说,比赛的结果是从标准输入中读取的,我必须将最终排名按照已解决问题的数量降序打印到屏幕上。这是我的代码。

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

当我要编译代码时,编译器发现了错误

cannot convert 'std::vector' to 'void*' for argument '1' to '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]

但实际上,just use 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++ 中对结构 vector 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34109586/

相关文章:

c - Qsort结构数组比较函数

c - qsort 反转字符串的顺序

c++ - 为什么要使用 constexpr

c++ - 改变三角形的颜色

c - 单一函数可处理两种类型的链表

c++ - 有什么区别: Creating structure pointer inside a structure of the same type with the keyword struct

c - qsort 函数导致问题

c++ - 在派生类中初始化具有依赖类型名称的基子对象

c++ - 在没有 C++ 11 的情况下使用 char16_t、char32_t 等?

ruby - 奇怪的 Ruby 行为