歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C++實現按1的個數排序

C++實現按1的個數排序

日期:2017/3/1 9:51:50   编辑:Linux編程

題目內容:有一些0、1字符串,將其按1的個數的多少的順序進行輸出。

輸入描述:本題只有一組測試數據。輸入數據由若干數字組成,它是由若干個0和1組成的數字。

輸出描述:對所有輸入的數據,按1的個數進行生序排序,每行輸出一個數字。

題目分析:

(1)定義一個string型向量容器存儲輸入的數據;定義一個string型變量作為向量容器的元素;定義排序方法,若‘1’的個數不相等則按‘1’的個數從小到大的順序返回,否則按字符串從小到大的順序返回

(2)從鍵盤讀入字符串,將讀入的每個字符串插入向量容器

(3)對向量容器中的元素按照設定的比較函數進行排序

(4)遍歷向量容器並輸出每一個元素

參考代碼:


#include <fstream>

#include <iostream>

#include <string>

#include <vector>

#include <algorithm>

using namespace std;

bool myComp(const string &s1,const string &s2)

{

int c1=count(s1.begin(),s1.end(),'1');

int c2=count(s2.begin(),s2.end(),'1');

return c1!=c2?c1<c2:s1<s2;

}

int main(int argc,char * argv[])

{

vector<string> vstr;

string str;

while(cin>>str)

{

vstr.push_back(str);

if(cin.get()=='\n')

{

break;

}

}

sort(vstr.begin(),vstr.end(),myComp);

for(vector<string>::iterator it=vstr.begin();it<vstr.end();it++)

cout<<*it<<endl;

system("pause");

return 0;

}

運行結果:

Copyright © Linux教程網 All Rights Reserved