描述
You have a lot of photos whose file names are like:
beijing1
beijing10
beijing8
shanghai233
As you can see, all names have exactly two parts: the string part and the number part. If you sort the files in lexicographical order “beijing10” will go before “beijing8”. You do not like that. You want to sort the files first in lexicographical order of the string part then in ascending order of the number part. Can you write a program to work it out?
输入
The first line contains an integer N denoting the number of files. (1 <= N <= 100)
The following N lines each contain a file name as described above.
It is guaranteed that the number part has no leading zeroes and is no more than 1000000.
输出
The sorted files one per line.
样例输入
4
beijing1
beijing10
beijing8
b233
样例输出
b233
beijing1
beijing8
beijing10
题意:
一个字符串由两部分组成,第一部分是英文字母,第二部分是数字。现在要先按第一部分的字典序排序如果第一部分相同则按第二部分升序排序。
思路:
直接将这个字符串分成两部分,然后分别按第一部分和第二部分排序。其中用到了 std::stoi函数是直接将string类型转为int型的函数。
#include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
struct node
{
string str;
int num;
};
bool cmp(node A, node B) {
if (A.str == B.str) {
return A.num < B.num;
}
return A.str < B.str;
}
vector<node>p;
int main()
{
int n,len,index;
cin >> n;
string s;
for (int i = 0; i < n; ++i) {
cin >> s;
index = 0;
len = s.length();
for (int j = 0; j < len; ++j) {
if (s[j] >= '0' && s[j] <= '9') {
index = j;
break;
}
}
node tmp;
tmp.str = s.substr(0,index);
tmp.num = std::stoi(s.substr(index,len));
p.push_back(tmp);
}
sort(p.begin(),p.end(),cmp);
for (int i = 0; i < p.size(); ++i) {
cout << p[i].str << p[i].num << endl;
}
}