当然,您可以使用 set_intersection、set_difference 和 set_union 来解决问题。这是一个关于如何在您的问题中使用这些功能的示例:
std::set<std::string> findQueryMatches(std::map<std::string,
std::set<std::string>>& index, std::string sentence) {
std::set<std::string> url_set;
std::stringstream ss;
std::string str;
ss.str(sentence);
while(ss >> str) {
if(str[0] == '-') { //difference
std::set<std::string> difference_data;
std::set_difference(url_set.begin(), url_set.end(), index[str.substr(1, str.size() - 1)].begin(), index[str.substr(1, str.size() - 1)].end(),
std::inserter(difference_data, difference_data.begin()));
url_set = difference_data;
std::cout<<str<<": ";
for(auto const& x: url_set) {
std::cout<<x<<' ';
}
std::cout<<'\n';
} else if(str[0] == '+') { //intersection
std::set<std::string> intersection_data;
std::set_intersection(index[str.substr(1, str.size() - 1)].begin(), index[str.substr(1, str.size() - 1)].end(), url_set.begin(), url_set.end(),
std::inserter(intersection_data, intersection_data.begin()));
url_set = intersection_data;
std::cout<<str<<": ";
for(auto const& x: url_set) {
std::cout<<x<<' ';
}
std::cout<<'\n';
} else { //union
std::set<std::string> union_data;
std::set_union(index[str].begin(), index[str].end(), url_set.begin(), url_set.end(),
std::inserter(union_data, union_data.begin()));
url_set = union_data;
std::cout<<str<<": ";
for(auto const& x: url_set) {
std::cout<<x<<' ';
}
std::cout<<'\n';
}
}
return url_set;
}
请记住,您必须为 set_intersection、set_difference 和 set_union 提供一个输出运算符(看看这个:https ://en.cppreference.com/w/cpp/algorithm/set_difference或者这个如何找到两个 std 的交集: :在 C++ 中设置?)。这些输出运算符可以这样定义:
template <class InputIterator1, class InputIterator2, class OutputIterator>
OutputIterator std::set_union ( InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2,
OutputIterator result );
template <class InputIterator1, class InputIterator2, class OutputIterator>
OutputIterator std::set_intersection ( InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2,
OutputIterator result );
template <class InputIterator1, class InputIterator2, class OutputIterator>
OutputIterator std::set_difference ( InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2,
OutputIterator result );
例如给定这个数据:
www.shoppinglist.com
EGGS! milk, fish @ bread cheese
www.rainbow.org
red ~green~ orange yellow blue indigo violet
www.dr.seuss.net
One Fish Two Fish Red fish Blue fish !!!
www.bigbadwolf.com
I'm not trying to eat you milk,
还有这句话:
milk, +milk, Blue +fish -Fish
结果是:
milk,: www.bigbadwolf.com www.shoppinglist.com
+milk,: www.bigbadwolf.com www.shoppinglist.com
Blue: www.bigbadwolf.com www.dr.seuss.net www.shoppinglist.com
+fish: www.dr.seuss.net www.shoppinglist.com
-Fish: www.shoppinglist.com
干杯!