我的函数search_intersection接收一个set <set<string> >& inter_section 。
我想在inter_section获取所有子集的交集。
例如,如果:
inter_section = { { lion, cat } , {lion, bird}, {lion, cat, bird} }我想要:
result = { lion }目前我做到了这一点
set<string> search_intersection(set <set<string> >& inter_section) { set <set<string> >::iterator iter_ss; set <string> result; for (iter_ss = inter_section.begin(); iter_ss != inter_section.end(); ++iter_ss) { set_intersection(iter_ss.begin(),iter_ss.end(), result.begin(),result.end(), std::inserter(result.begin(),result.end())); } cout << endl; return result; }非常感谢!
My function search_intersection receive a set <set<string> >& inter_section.
I want get the intersection over all subsets in inter_section.
For example if:
inter_section = { { lion, cat } , {lion, bird}, {lion, cat, bird} }I want:
result = { lion }At the moment I did this
set<string> search_intersection(set <set<string> >& inter_section) { set <set<string> >::iterator iter_ss; set <string> result; for (iter_ss = inter_section.begin(); iter_ss != inter_section.end(); ++iter_ss) { set_intersection(iter_ss.begin(),iter_ss.end(), result.begin(),result.end(), std::inserter(result.begin(),result.end())); } cout << endl; return result; }Thanks a lot!
最满意答案
我们再试一次:(未编译的代码)
set<string> search_intersection(const set <set<string> > &inter_section) { set <string> result; set <set<string> >::iterator iter = inter_section.begin (); if ( iter != inter_section.end ()) { result = *iter; for ( ++iter; iter != inter_section.end (); ++iter ) { set <string> temp; // intersect *iter and result, put into temp set_intersection( iter->begin(), iter->end (), result.begin(), result.end(), std::inserter(temp,temp.end())); result = temp; } } return result; }请注意,对set_intersection的调用会传递迭代器指向的集合的开始/结束。 此外,至少有两个地方应该将const应用于此代码。
您也不set_intersection的结果写入其中一个输入。 因此是一个临时变量。
Let's try again: (Uncompiled code)
set<string> search_intersection(const set <set<string> > &inter_section) { set <string> result; set <set<string> >::iterator iter = inter_section.begin (); if ( iter != inter_section.end ()) { result = *iter; for ( ++iter; iter != inter_section.end (); ++iter ) { set <string> temp; // intersect *iter and result, put into temp set_intersection( iter->begin(), iter->end (), result.begin(), result.end(), std::inserter(temp,temp.end())); result = temp; } } return result; }Note that the call to set_intersection passes the begin/end of the set pointed to by the iterator. Also, there are at least two places where const should be applied to this code.
You can't write the results of set_intersection into one of the inputs, either. Hence a temp variable.
更多推荐
发布评论