【发布时间】:2011-09-16 00:20:33
【问题描述】:
我有一个程序试图按字母顺序对某些名称进行排序。我运行它,它没有任何错误,但名称没有排序。我比较了 2 个名称,看看哪个应该在数组中移动。
代码如下:
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];
};
我是否必须将它们转换为字符串,因为它们是字符数组?我有点迷茫,想弄清楚如何让它正确排序。
【问题讨论】:
-
文本字符串在 C++ 中通常最好用
std::string表示。const char*也是可能的,但char[]在大多数情况下并不是一个真正好的解决方案。 -
这看起来像家庭作业,如果是这样,请适当地标记它。如果不是,则使用 std::lexicographical_compare 移至 std::string 和 std::sort。
-
为什么不直接使用
std::vector、std::string和std::sort?然后,您的代码将减少为一行。