如何在内容保持关联的同时按字母顺序对结构数组进行排序
How do i sort an array of structs alphabetically while contents stay associated
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
。
- 按字母顺序对结构内数组变量中的名称进行排序
- 有了memory_order_relaxed,原子变量的总修改顺序如何在典型体系结构上得到保证
- C++ MDC final-在字符类型的数组结构中按字母顺序对记录中的名称进行排序
- 为什么结构属性声明和初始化顺序的行为是这样的?
- 按字母顺序对结构数组进行排序
- C++中的结构是否按顺序分配内存?每次都以某种方式获得指针比较的正确答案
- 结构根据空基类顺序更改大小
- 结构中的位顺序不是我所期望的
- 为什么在未由语言本身定义的结构字节中的位字段顺序
- Arduino:联合中的结构顺序
- 编译时随机化结构成员的顺序
- 结构化绑定的标识符是否按顺序初始化?
- 按字母顺序打印结构输入C
- 具有类层次结构时按什么顺序调用方法
- 结构对齐填充、最大填充大小和结构成员顺序
- 一种按排序顺序保持元素的数据结构,支持快速插入和计算连续元素之间的最大差异
- c++设置了保持插入顺序的数据结构
- 使用提升 Qi 解析为结构的随机顺序
- 结构/对象内的存储顺序
- 简单的输入/输出控制台应用程序,不按给定的顺序(结构)打印问题