【问题标题】:c++ sorting names alphabeticallyc++ 按字母顺序排序名称
【发布时间】: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::vectorstd::stringstd::sort?然后,您的代码将减少为一行。

标签: c++ string sorting


【解决方案1】:

问题在于这一行:

if ((student_list[currentindex].lname) < (student_list[smallestnum].lname))

它不比较字符串字符,而是比较内存地址。

如果您仍想使用char 数组,则必须使用strcmp 函数。不过,我建议您改用string

【讨论】:

  • 谢谢,我使用了strcmp,它可以工作。我不得不使用 char 来完成作业。
【解决方案2】:

问题出在这一行:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多