01 串的排序问题:
- //首先按长度排序,
- //长度一样,按'1'的个数排序,
- //‘1’的个数一样时,就按ASCII排序
- #include <iostream>
- #include <string>
- #include <set>
- #include <algorithm>
- #include <fstream>
- //if there is not included fstream libary ,we will get the bottom error:
- ///main.cpp|26|error: variable `std::ifstream cin' has initializer but incomplete type|
- //||=== 完成的Build: 1 个错误, 0 个警告 ===|
- using namespace std;
- struct cmp//比较算法:从'1'的个数 按小到大排
- {
- //重载()操作
- bool operator () (const string &s1,const string &s2)//返回1 ,0 ,-1
- {
- if(s1.length()!=s2.length())
- return s1.length()<s2.length(); //返回比较长度的逻辑值
- int c1 = count(s1.begin(),s1.end(),'1');
- int c2 = count(s2.begin(),s2.end(),'1');
- return (c1!=c2?c1<c2:s1<s2); //c1等于c2时返回c1<c2的逻辑值,否者返回ASCII值
- }
- };
- int main(int argc,char *argv[])
- {
- multiset<string,cmp>ms;//Why choose multiset data struct in this place?
- ifstream cin("aaa.txt");
- string str;
- while(cin>>str)
- {
- ms.insert(str);
- }
- multiset<string,cmp>::iterator iter;
- for(iter=ms.begin();iter!=ms.end();iter++)
- {
- cout<<*iter<<endl;
- }
- return 0;
- }