c++按字母顺序排序名称
c++ sorting names alphabetically
我有一个程序,它试图按字母顺序对一些名字进行排序。我运行它,它没有任何错误,但名称没有排序。我比较了两个名字,看看哪一个应该在数组中移位。
代码如下:
void sort_names(char array[])
{
const int arraysize = 5;
// Step through each element of the array
for (int startindex = 0; startindex < arraysize; startindex++)
{
int smallestnum = startindex;
for (int currentindex = startindex + 1; currentindex < arraysize; currentindex++)
{
// If the current element is smaller than our previously found smallest
if ((student_list[currentindex].lname) < (student_list[smallestnum].lname))
// Store the index
smallestnum = currentindex;
}
// Swap our start element with our smallest element
swap(student_list[startindex], student_list[smallestnum]);
}
}
我的结构是这样的:
struct student {
char fname[30];
char lname[30];
};
我是否必须将这些转换为字符串,因为它们是字符数组?我有点迷路了,想弄清楚如何使它正确排序
问题是在这一行中:
if ((student_list[currentindex].lname) < (student_list[smallestnum].lname))
它不比较字符串字符,而是比较内存地址。
如果您仍然想使用char
数组,则必须使用strcmp
函数。但是,我建议您使用string
。
问题出在这一行:
if ((student_list[currentindex].lname) < (student_list[smallestnum].lname))
行比较指针,但不比较内容。
应该是:
if ( strcmp( student_list[currentindex].lname, student_list[smallestnum].lname ) < 0 )
另一种替代方法是使用std::string,它具有内置比较。例如:
struct student {
std::string fname;
std::string lname;
};
相关文章:
- vim 标签导航,使用 VIM 或 CTAG 更改排序顺序
- 集成多态可扩展排序顺序
- 如何修改函数以按C++的排序顺序插入每个项目
- 按排序顺序将节点插入链表
- 在C std :: Priority_queue中反向字母排序顺序的简单方法
- std::map 的排序顺序取决于输入值
- 一种按排序顺序保持元素的数据结构,支持快速插入和计算连续元素之间的最大差异
- 将随机数插入排序顺序为C++的数组中
- C++链表-按排序顺序打印
- STL 按排序顺序存储数字
- 基于最大公分的排序顺序
- 用于插入大部分排序数据的数据结构,这些数据将保持排序顺序
- 将范围有限的浮点数转换为无符号的整数,以保持排序顺序和精度
- 在排序时更改排序顺序是否是未定义的行为
- 排序顺序问题
- QSqlQuery 忽略 SQLite DB 的排序顺序
- 按排序顺序迭代 std::vector
- 使用不同的比较保持相同的排序顺序
- 按排序顺序更新文件
- 如何按排序顺序生成数组的所有排列