解1:
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <cctype>
using namespace std;
bool comparator(string a, string b)
{
char c1,c2;
for(int i = 0 ; i < a.length() ; ++i)
{
if((c1 = tolower(a[i])) != (c2 = tolower(b[i])))
{
return c1 < c2;
}
}
return true;
}
int main()
{
vector<string> vec;
string temp;
cin >> temp;
while(temp != "#")
{
vec.push_back(temp);
cin >> temp;
}
sort(vec.begin(),vec.end(),comparator);
for (vector<string>::const_iterator iter = vec.begin() ;
iter < vec.end() ; ++iter)
{
cout << *iter << endl;
}
return 0;
}
解2:
01.#include "iostream"
02.#include "algorithm"
03.using namespace std;
04.
05.class person
06.{
07.private:
08. char name[10];
09. char num[10];
10. friend class compute; //类compute必须声明为类person的友元类
11.public:
12. bool friend cmp(const person &a,const person &b); //友元函数从语法上看,它与普通函数一样,友元函数的特点是能够访问类中的私有成员的非成员函数。
13.};
14.class compute
15.{
16.private:
17. person pn[3]; //表示3个用户
18.public:
19. void setdata(); //通过键盘输入3个用户的数据
20. void sort_name(); //将数组pn表示的用户信息按姓名的字典序进行排序
21. void print(); //按照指定格式输出用户信息
22.};
23.void compute::setdata()
24.{
25. for(int i=0;i<3;i++)
26. cin>>pn[i].name>>pn[i].num;
27.}
28.bool cmp(const person &a,const person &b)
29.{
30. return strcmp(a.name,b.name)<0;
31.}
32.void compute::sort_name()
33.{
34. sort(pn,pn+3,cmp);
35.}
36.void compute::print()
37.{
38. for(int i=0;i<3;i++)
39. cout<<pn[i].name<<" "<<pn[i].num<<endl;
40.}
41.int main(void)
42.{
43. compute com;
44. cout<<"请输入用户的数据:"<<endl;
45. com.setdata();
46. com.sort_name();
47. cout<<"将用户信息按姓名的字典序进行排序:"<<endl;
48. com.print();
49. system("pause");
50. return 0;
51.}