c++删除txt文件重复行

180it 2020-10-13 AM 1696℃ 0条

概述

利用stl特性来实现文件重复行删除,先将文本行与所属行数(保证输出顺序不变)成对插入set容器,然后将set容器中元素转移至map中根据文本行所属行数进行排序,以达到删除重复行且文本顺序不变。时间复杂度(2n),空间复杂度(k+n)(k为string转hash值的最大值)

实现

#include<map>
#include<string>
#include<fstream>
#include<iostream>
#include<unordered_set>

using namespace std;

struct myHash//使set根据pair的第二元素建立hash
{
    size_t operator()(pair<int, string> __val) const
    {
        return hash<string>()(__val.second);
    }
};

struct myEqual//使set根据pair第二元素判断两pair是否相等
{
    bool operator()(pair<int, string> val1, pair<int, string> val2) const
    {
        return val1.second == val2.second;
    }
};

int main() {
    long long count = 0;
    std::fstream in_out;
    map<int, string> int_string;
    unordered_set<pair<int,string>, myHash, myEqual> text;
    //
    in_out.open("input.txt", std::ios::in | std::ios::binary);
    pair<int, string> temp;
    while (getline(in_out,temp.second)) {
        temp.first = count++;
        text.insert(temp);
    }
    in_out.close();
    //
    for (unordered_set<pair<int, string>>::iterator it = text.begin(); it != text.end(); it++)
        int_string.insert(*it);//插入map中,自动按照pair第一元素排序
    in_out.open("output.txt", std::ios::trunc | std::ios::out);
    for (map<int, string>::iterator it = int_string.begin(); it != int_string.end(); it++)
        in_out << (*it).second << endl;
    in_out.close();
    system("pause");
}

支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

c++删除txt文件重复行