我正在尝试编写一个程序,让用户输入三个名称并对它们进行排序。 条件是每个名字都像“名字姓氏”一样输入,然后我需要按姓氏对名字进行排序,但如果两个条目的姓氏相同,我需要按名字排序。
我已经解决了如何只对名字或姓氏进行排序的问题,但我对如何对两者进行排序感到困惑。关于如何在不使用数组或 <algorithm>
的情况下实现更多条件排序的任何想法在 C++ 中?
对于每个输入,我这样做是为了将输入拆分为名字和姓氏以小写:
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;
}
最佳答案
要交换名字和姓氏,请使用以下技巧:
- 反转整个字符串
- 反转字符串中的各个名称
为此,您应该编写一个函数来反转两个索引之间的字符串,并且您需要使用 string::find()
(或循环)来查找两个索引之间的空格名字。
要对三个项目进行排序,请使用以下技巧:
- 对前两项排序
- 对最后两项进行排序
- 对前两项排序
同样,对两个项目进行排序非常适合一个函数。
提示:
void reverse( string& s, int first, int last );
void sort( string& a, string& b ); // swap a and b if !(a < b)
关于c++ - 如何在 c++ 中没有数组/算法的情况下在两个条件下对字符串进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48053159/