使STL sort对Log进行排序

来源:互联网 发布:秋季长裙淘宝网 编辑:程序博客网 时间:2024/05/09 04:35
 #include "iostream"
 #include "string.h"
 #include "iostream"
 #include "fstream"
 #include <vector>
 #include <algorithm>

 using namespace std;
 typedef struct url_n_time
 {
   string url;
   int times;
   bool operator <(const url_n_time& i1)const
   {
     return times < i1.times;
   }
 }url_n_time;
 /*
 bool operator <(const url_n_time& i1, const url_n_time i2)
 {
   if(i1.times >= i2.times)
   {
     return true;
   }
   else
   {
     return false;
   }
 }*/
 vector<url_n_time> vec_url_n_time(0);

 bool url_times_cmp(const url_n_time& url1, const url_n_time& url2)
 {
   if(url1.times >= url2.times)
   {
     return true;
   }
   else
   {
     return false;
   }
 }

 int main()
 {
   char ch_array[201];
   ifstream in("1.txt");
   string str;
   string str_last;
   vector<string> vec_str(0);
   int lineNum=0;
   url_n_time url_n_time_temp;
   in.getline(ch_array, 200);
   str_last = ch_array;
   url_n_time last_url_data;
   last_url_data.url = str_last;
   last_url_data.times = 1;
   while(in.getline(ch_array,200))
   {
     lineNum++;
     str = ch_array;
     if( !str.compare(str_last) )
     {
       ++last_url_data.times;
     }
     else
     {
       vec_url_n_time.push_back(last_url_data);
       str_last = str;
       last_url_data.url = str_last;
       last_url_data.times = 1;
     }
   }
   vec_url_n_time.push_back(last_url_data);
   cout << "total urls:" << vec_url_n_time.size() << endl;
 /*
   sort(vec_url_n_time.begin(), vec_url_n_time.end());
 */
   sort(vec_url_n_time.begin(), vec_url_n_time.end(),url_times_cmp);

   vector<url_n_time>::iterator it;
   for(it=vec_url_n_time.begin(); it!=vec_url_n_time.end(); it++)
   {
     /*cout << "url:" << it->url.c_str() << "times:" << it->times << endl;*/
     cout << it->url.c_str() << " " << it->times << endl;
   }
   return 0;
 }
 

原创粉丝点击