我正在尝试做一个用户输入三个名字然后进行排序的程序。条件是每个名称输入像“firstname lastname”,然后我需要在姓氏上对名称进行排序,但如果两个条目的姓氏相同,我需要对名字进行排序。
我已经解决了如何只对名字或姓氏进行排序,但我仍然坚持如何对两者进行排序。如何在不使用c ++中的数组或<algorithm>
的情况下实现更多条件排序的任何想法?
对于每个输入,我这样做是为了将输入分割为firstname和lastname为小写:
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库中的strcat)将两个字符串连接在一起。使用“”分隔它们。这将保留字典顺序并将问题减少到已经解决的问题:)
使用您已经创建的6 if子句来选择生成的(单个)字符串的正确顺序。
在c ++中,您可以使用operator +来连接字符串。
如果您无法打印生成的单个字符串(打印和比较的顺序不同) - 您必须将它们拆分(strtok)并在打印前反转名/姓。
@编辑
此外,当我们在它时,您可以使用std::cin >> firstName >> lastName
读取字符串(它将读取直到第一个空格)并使用std::string::operator[]在同一循环中使用char将char小写为char来访问字符