例题:有一个文本1.txt,内容有N行:
1111
3333
1111
3333
2222……
写一段c++的代码可以将重复行去除,内容变为:
1111
3333
2222……
代码如下:
#include <iostream>
#include <string>
#include <fstream>
#include <set>
using namespace std;
ifstream & open_file(ifstream &in, const string & file)
{
in.close();
in.clear();
in.open(file.c_str());
return in;
}
int main()
{
set <string> ss;
set <string>::iterator iter;
ifstream infile;
ofstream ofile;
if (!open_file(infile, "1.txt"))
{
cerr << "No input file!" << endl;
return EXIT_FAILURE;
}
string textline;
while (getline(infile, textline))
ss.insert(textline);
ofile.open("1.txt");
for (iter = ss.begin();iter != ss.end();iter++)
ofile << *iter << endl;
return 0;
}