如何在没有 c++ 中的数组/算法的情况下对两个条件的字符串进行排序

How to sort strings on two conditions without an array/algorithms in c++?

本文关键字:两个 条件 排序 字符串 情况下 c++ 算法 数组      更新时间:2023-10-16

我正在尝试做一个程序,其中用户输入三个名称并对其进行排序。 条件是每个名字都像"名字姓氏"一样输入,然后我需要按姓氏对名字进行排序,但如果两个条目的姓氏相同,我需要对名字进行排序。

我已经解决了如何仅对名字或姓氏进行排序的问题,但是我陷入了如何对两者进行排序的问题。有什么想法如何在不使用 c++ 中数组或<algorithm>的情况下实现更多的条件排序?

对于每个输入,我这样做是为了将输入拆分为名字,将姓氏拆分为小写:

cout << "Input name1: " << endl;
getline(cin, input1);
input1_old = input1;
size_t found = input1.find(space);
for (int i = 0; i < input1.size(); i++)
{
    input1[i] = tolower(input1[i]);
}
input1Last = input1.substr(found + 1, string::npos);
input1First = input1.substr(0, found);

然后我像这样"排序":

if (input1Last <= input2Last && input2Last <= input3Last)
{
    cout << input1_old << 'n' << input2_old << 'n' << input3_old << endl;
}
else if (input1Last <= input3Last && input3Last <= input2Last)
{
    cout << input1_old << 'n' << input3_old << 'n' << input2_old << endl;
}
else if (input2Last <= input1Last && input1Last <= input3Last)
{
    cout << input2_old << 'n' << input1_old << 'n' << input3_old << endl;
}
else if (input2Last <= input3Last && input3Last <= input1Last)
{
    cout << input2_old << 'n' << input3_old << 'n' << input1Last << endl;
}
else if (input3Last <= input1Last && input1Last <= input2Last)
{
    cout << input3_old << 'n' << input1_old << 'n' << input2_old << endl;
}
if (input3Last <= input2Last && input2Last <= input1Last)
{
    cout << input3_old << 'n' << input2_old << 'n' << input1Last << endl;
}

假设这是一个家庭作业问题,你不应该使用宏或试图巧妙地避免限制:

使用字符串连接(标准 C 库中的 strcat(将两个字符串连接在一起。使用" "分隔它们。这将保留词典顺序并将问题减少到已经解决的问题:)

使用您已经创建的 6 if 子句来选择结果(单个(字符串的正确顺序。

在 c++ 中,你可以只使用 operator+ 来连接字符串。

如果无法打印生成的单个字符串(打印和比较的顺序不同( - 则必须在打印前拆分它们(strtok(并反转名字/姓氏。


@EDIT此外,当我们使用它时,您可以使用 std::cin >> firstName >> lastName 来读取字符串(它将读取直到第一个空格(,并使用 std::string::operator[] 在同一循环中将它们逐

个小写以访问字符

要交换名字和姓氏,请使用以下技巧:

  • 反转整个字符串
  • 反转字符串中的各个名称

为此,您应该编写一个函数来反转两个索引之间的字符串,并且需要使用string::find()(或循环(来查找名称之间的空格。

要对三个项目进行排序,请使用以下技巧:

  • 对前两个项目进行排序
  • 对最后两个项目进行排序
  • 对前两个项目进行排序

同样,对两个项目进行排序对于一个功能来说是完美的。

提示:

void reverse( string& s, int first, int last );
void sort( string& a, string& b );  // swap a and b if !(a < b)