如何在内容保持关联的同时按字母顺序对结构数组进行排序

How do i sort an array of structs alphabetically while contents stay associated

本文关键字:顺序 结构 数组 排序 关联      更新时间:2023-10-16
struct Album {
  string title;
  string year;
  string track;
  vector<string> tracks;
}MyAlbums[5];

int j;
Album temp;
for(int i = 1; i < 5; i++)
{
  j = i - 1;
  while( j >= 0 && strcmp( MyAlbums[j+1].title[0], MyAlbums[j].title[0]) < 0 ){
    temp =  MyAlbums[j + 1];
    MyAlbums[j+1] = MyAlbums[j];
    MyAlbums[j] = temp;
    j--;
  }
}

给我这个:从"字符"到"常量字符*"的无效转换[-允许]

C++

struct Album {
  string title;
  string year;
  string track;
  vector<string> tracks;
  bool operator<(const Album &a) const
  {
      return title.compare(a.title) > 0;
  }
} MyAlbums[5];
std::sort(std::begin(MyAlbums), std::end(MyAlbums));

C++11

std::sort(std::begin(MyAlbums), std::end(MyAlbums), [](const Album &a1, const Album &a2 ){
    return a1.title.compare(a2.title) > 0;
});

出现错误,因为您正在比较MyAlbums[j+1].title[0] ; std::string的第一个元素,它是一个char(或const char(而不是一个const char*

可能你想要:

strcmp(MyAlbums[j+1].title.c_str(), MyAlbums[j].title.c_str())) < 0

这是语法正确的,但不确定逻辑。

由于您使用的是C++,因此可以考虑使用std::sort(..)

另一种选择是更改您的设计并使用 std::map(..) .在这里,您的所有数据都将按顺序排列,可以使用迭代器(向前或向后(进行迭代。另一方面,您将可以使用地图键轻松访问。

您正在使用 STL 类,那么为什么要在有 title.compare(title2) 时使用 strcmp

也以不正确的方式使用它,因为您正在尝试比较两个char(title[0](而不是char*

您可以使用自定义比较器,例如

struct cmp_str {
  bool operator()(const Album &a, const Album &b) {
    return a.title.compare(b.title) < 0;
  }
};

并使用std:sort(..)相应地对集合进行排序

strcmp需要const char*

MyAlbums[j+1].title[0]返回一个char

最好的办法是使用 std::sort 并为Album定义operator<()。您也可以在title上使用.c_str()

有关 strcmp 的更多信息。

std::string有一个可以使用的比较方法。

while( j >= 0 && MyAlbums[j+1].title.compare(MyAlumbus[j].title) < 0)
{ ... }

MyAlumbus[j].title[0]在拉出第一个字符的std::string上调用重载operator[]

strcmp ( const char * str1, const char * str2 )strcmp的签名。它期望一个char *,而你只是提供一个char