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::set
s. 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::vector
s, 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.