读书人

删除重复字符串的有关问题~

发布时间: 2012-03-01 10:25:46 作者: rapoo

删除重复字符串的问题~急啊!!!
继续请教各位一下~

我要将txt文件里的重复字符串删除,之前有个朋友告诉我说C++里可以用sort函数先排序,然后用unique就可以了~可我不大懂,有没有人可以帮忙再给个提示...

txt文件里的存储为如下形式:(就是一些以空格为分界的字符串)

101015 20107600025 101025 20307600016 101025

具体如何实现删除重复的~

[解决办法]

C/C++ code
 
#include <iostream>
#include <set>
using namespace std;

int main ()
{
char myints[] = "101015 20107600025 101025 20307600016 101025";

set <char> myset (myints,myints+sizeof(myints)/sizeof(char));

set <char>::iterator it;

cout < < "myset contains:";
for ( it=myset.begin() ; it != myset.end(); it++ )
cout < < " " < < *it;

cout < < endl;

return 0;
}

[解决办法]
C/C++ code
#include "stdafx.h"#include <iostream>#include <string>#include <set>#include <fstream>using namespace std;int _tmain(int argc, _TCHAR* argv[]){    set<string> set_string;    string temp_str;    char buffer[128];    bool b_flag = true;    size_t icount = 0;    fstream file_in("D:\\test.txt", ios_base::in);    fstream file_out("D:\\result.txt", ios_base::out);    if (!file_in.is_open())    {        cout << "文件打开失败" << endl;        return -1;    }    if (!file_out.is_open())    {        cout << "文件打开失败" << endl;        return -1;    }    while (!file_in.eof())    {        file_in.getline(buffer, 128, ' ');        temp_str = string(buffer);        temp_str = temp_str.substr(0, temp_str.find(' '));        icount = set_string.size();        if (b_flag)        {            set_string.insert(temp_str);            b_flag = false;        }        set_string.insert(temp_str);        if (icount == set_string.size())        {            continue;        }        file_out<<temp_str.c_str() << " ";    }    file_in.close();    file_out.close();    cout << " OK! " << endl;    return 0;} 

读书人网 >C++

热点推荐