功能:对数字字符串按照数字的大小进行排序,输出相同字符串的个数
如数字字符串序列为:
1 2 3 123 1 2 3 123 234 2345 6 789 789
输出:
#include <vector>
#include <string>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <map>
using namespace std;
struct CmpByKeyNum
{
bool operator()(const string& k1, const string& k2)
{
if (k1.length() != k2.length())
return k1.length() < k2.length();
else
return k1 < k2;
}
};
int main()
{
vector<string> vec;
char buf[10] = "1";
vec.push_back(buf);
vec.push_back("2");
vec.push_back("3");
vec.push_back("123");
vec.push_back("1");
vec.push_back("2");
vec.push_back("3");
vec.push_back("123");
vec.push_back("234");
vec.push_back("2345");
vec.push_back("6");
vec.push_back("789");
vec.push_back("789");
map<string,int,CmpByKeyNum> words;
vector<string>::iterator it = vec.begin();
for(it; it != vec.end(); ++it)
{
if(words.find(*it) != words.end() )
{
int i = words[*it];
++i;
words[*it] = i;
}
else
{
words.insert(map<string,int>::value_type(*it,1));
}
}
map<string,int,CmpByKeyNum>::iterator mapit = words.begin();
for(mapit;mapit != words.end();++mapit)
{
cout<< mapit->first<<" "<<mapit->second<<endl;
}
return 0;
}