0

我目前正在编写一个代码来交叉两个文本文件集。我是 C++ 新手,所以编码不好。请告诉我我在这段代码中遗漏了什么或输入错误。谢谢你帮助我。

set<string> file1;
set<string> file2;
set<string> ofile;

string data1[] = { "X.txt"};
string data2[]={"Y.txt"};

file1.insert(data1,data1);
file2.insert(data2, data2);

cout<< "file1 is" << file1<<endl;

set_intersection(file1.begin(),file1.end(),file2.begin(),file2.end(),
    inserter(file1, file1.begin()));

 cout<<"file1 * file2 is" << ofile<< endl;
4

1 回答 1

2

Assuming you want to get integer data from the files x.txt and y.txt, you could do something like this:

typedef int T;

std::ifstream in1("x.txt");
std::ifstream in2("y.txt");

std::set<T> set1{ std::istream_iterator<T>(in1), 
                  std::istream_iterator<T>() };

std::set<T> set2{ std::istream_iterator<T>(in2),
                  std::istream_iterator<T>() };

std::set_intersection(set1.begin(), set1.end(), 
                      set2.begin(), set2.end(),
                      std::ostream_iterator<T>(std::cout, "\n"));

If the contents of the files are something other than integers, you can change the type of T to suit (e.g., if you have a set of words, you might want to use std::string instead of int).

As it stands right now, this just writes the result to standard output. You might want to change that to put the output in some other collection instead.

This also currently puts the initial input data into std::sets. Despite the name set_intersection the data doesn't really need to be in an std::set. It really just needs to be stored in sorted order. You could, for example, put the data into std::vectors, then sort them and (if necessary) use std::unique to ensure unique elements in each vector. I bring this up primarily because it'll typically run faster and use (substantially) less memory.

于 2015-03-16T19:54:20.923 回答