文件內容比較

這是一個c++ 編程思想(2卷) 上的一個示例,試寫了一下,算是對模板的一個練習

#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <string>
#include <set>
#include <stdexcept>

using namespace std;  
typedef vector<string> vecstr;
typedef set<string>  setstr;
typedef ostream_iterator<string> outstr;

const bool TRUE = 1;
const bool FALSE = 0;

/*
void printElement(string str){
  cout<<str<<endl; 
}*/
//這個類與上述函數在下面的調用中作用相同
class printElement{
public:
 void operator ()(string &str){
  cout<<str<<endl;
 }
};

template<class T,class V>
void AddElemtoContainter(T &s,const V &words)                                           //默認的是vector,list等
{
 s.push_back(words);
}

template<>
void AddElemtoContainter<setstr,string>(setstr &s,const string &words)                   //實例化set
{
 s.insert(words);
}

template <class T>
bool populate_set_from_file(T &s,const char* file_no)
{
 ifstream fin(file_no);
 string words;
 while(fin>>words){
  if (fin.fail())
  {
   cout<<"Error in fstream."<<endl;
   return FALSE;
  }
  AddElemtoContainter(s,words);
 }
 fin.close();
 return TRUE;
}

template<class Containter_type,class Value_type>
void Container_Differences(const Containter_type &t1,const Containter_type &t2,Containter_type &t3)
{
 Containter_type temp;
 Containter_type::const_iterator pos_Con_fst,pos_find_at;
 if(t1==t2) exit(0);
 pos_Con_fst = t1.begin();
 while (pos_Con_fst!=t1.end())
 {
  pos_find_at= find(t2.begin(),t2.end(),(*pos_Con_fst));
  if(pos_find_at==t2.end())
   AddElemtoContainter(temp,static_cast<string>(*pos_Con_fst));
  pos_Con_fst++;
 }
 pos_Con_fst = t2.begin();
 while (pos_Con_fst!=t2.end())
 {
  pos_find_at=find(t1.begin(),t1.end(),(*pos_Con_fst));
  if(pos_find_at==t1.end())
   AddElemtoContainter(temp,static_cast<string>(*pos_Con_fst));
  pos_Con_fst++;
 }
 temp.swap(t3);
}


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

 if(argc!=3)
 {
  cout << "compareFiles - copyright (c) Essam Ahmed 2000" << endl << endl;
  cout << "This program compares the conents of two files and prints" << endl
   << "the differences between the files to the screen" << endl << endl;
  cout << "Usage: compareFiles <file_name_1> <file_name_2>" << endl << endl;
  return 1;
 }
 outstr os(cout,"/n");
 setstr file1,file2,file3;
 populate_set_from_file(file1,argv[1]);
 cout<<"The element of the "<<argv[1]<<"is:"<<endl;
 copy(file1.begin(),file1.end(),os);

 populate_set_from_file(file2,argv[2]);
 cout<<"The element of the "<<argv[2]<<"is:"<<endl;
 copy(file2.begin(),file2.end(),outstr(cout,"/n"));

 Container_Differences<setstr,string>(file1,file2,file3);
 cout<<"The element of the difference is:"<<endl;
//在下式中printElement是唯一的,不能換成其他的名字。
// for_each(file3.begin(),file3.end(),printElement);
//在用類printElement時,要用printElement(),在這裏先生成了一個臨時對象,然後將其作爲參數傳遞。
 for_each(file3.begin(),file3.end(),printElement());
 system("pause");
 return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章