如何按字母顺序排序字符串? [英] How to alphabetically sort strings?
本文介绍了如何按字母顺序排序字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在尝试使用这个c ++程序按字母顺序对5个名称排序:
I have been trying to use this c++ program to sort 5 names alphabetically:
#include <iostream>
#include <cstring>
#include <conio.h>
using namespace std;
int main()
{
char names[5][100];
int x,y,z;
char exchange[100];
cout << "Enter five names...\n";
for(x=1;x<=5;x++)
{
cout << x << ". ";
cin >> names[x-1];
}
getch();
for(x=0;x<=5-2;x++)
{
for(y=0;y<=5-2;y++)
{
for(z=0;z<=99;z++)
{
if(int(names[y][z])>int(names[y+1][z]))
{
strcpy(exchange,names[y]);
strcpy(names[y],names[y+1]);
strcpy(names[y+1],exchange);
break;
}
}
}
}
for(x=0;x<=5-1;x++)
cout << names[x];
return 0;
}
如果我分别输入Earl,Don,Chris,Bill和Andy得到:
If I enter Earl, Don, Chris, Bill, and Andy respectively, I get this:
AndyEarlDonChrisBill
有人可以告诉我我的程序有什么问题吗?
Could someone please tell me whats wrong with my program?
推荐答案
或std :: multiset(如果您将允许重复项)的字符串,并且它将保持项目自动排序(如果你想要甚至可以更改排序标准)。
You could use std::set or std::multiset (if you will allow repeated items) of strings, and it will keep the items sorted automatically (you could even change the sorting criteria if you want).
#include <iostream>
#include <set>
#include <algorithm>
void print(const std::string& item)
{
std::cout << item << std::endl;
}
int main()
{
std::set<std::string> sortedItems;
for(int i = 1; i <= 5; ++i)
{
std::string name;
std::cout << i << ". ";
std::cin >> name;
sortedItems.insert(name);
}
std::for_each(sortedItems.begin(), sortedItems.end(), &print);
return 0;
}
输入:
- Gerardo
- Carlos
- Kamilo
- Angel
-
-
- Gerardo
- Carlos
- Kamilo
- Angel
- Bosco
>
output:
Angel
Bosco
Carlos
Gerardo
Kamilo
这篇关于如何按字母顺序排序字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文