To expand a bit on the answers you've already gotten, there are basically two factors to consider that you haven't specified. First, if there are duplicate elements in the input, do you want those considered for the output. For example, given input like:
st1 = "kok abc def kok...."
st2 = "kok bbr kok def ffe ...."
Since "kok" appears twice in both inputs, should "kok" appear once in the output or twice?
The second is your usage pattern. Do you have a pattern of reading all the input, then generating a single output, or is a more iterative, where you might read some input, generate an output, read some more input that's added to the previous, generate another output, and so on?
If you're going read all the input, then generate one output, you probably want to use std::vector
followed by std::sort
. If you only want each input to appear only once in the output, regardless of how often it appears in both inputs, then you'd follow that by std::unique
, and finally do your set_intersection
.
If you want to support iterative updates, then you probably want to use std::set
or std::multiset
(std::set
for each output to be unique, std::multiset
if repeated inputs should give repeated results).
Edit: based on the lack of duplication in the input, a really quick simple implementation would be something like:
#include <string>
#include <set>
#include <algorithm>
#include <iterator>
#include <sstream>
#include <iostream>
int main() {
std::string st1("abc def kok");
std::string st2("kok bbr def ffe");
std::istringstream s1(st1);
std::istringstream s2(st2);
// Initialize stringstreams. Whine about most vexing parse.
std::set<std::string> words1((std::istream_iterator<std::string>(s1)),
std::istream_iterator<std::string>());
std::set<std::string> words2((std::istream_iterator<std::string>(s2)),
std::istream_iterator<std::string>());
std::ostringstream common;
// put the intersection into common:
std::set_intersection(words1.begin(), words1.end(),
words2.begin(), words2.end(),
std::ostream_iterator<std::string>(common, " "));
std::cout << common.str(); // show the result.
return 0;
}