【发布时间】:2011-11-03 23:09:49
【问题描述】:
所以我们有set<string> a 和set<string> b,我们想要得到std::set<string> c,其中包含代表a - b 的项目(这意味着如果我们从@987654326 中删除所有项目,则从a 中剩下的内容@,如果b 包含超过a 或a 中不存在的项目,我们希望让它们与数字一样简单:5-6 = 0 而3-2 = 1)
【问题讨论】:
所以我们有set<string> a 和set<string> b,我们想要得到std::set<string> c,其中包含代表a - b 的项目(这意味着如果我们从@987654326 中删除所有项目,则从a 中剩下的内容@,如果b 包含超过a 或a 中不存在的项目,我们希望让它们与数字一样简单:5-6 = 0 而3-2 = 1)
【问题讨论】:
我想你想要 std::set_difference() 来自 <algorithm>。
#include <iostream>
#include <algorithm>
#include <set>
#include <string>
#include <iterator>
using namespace std;
set<string> a;
set<string> b;
set<string> result;
int main()
{
a.insert("one");
a.insert("two");
a.insert("three");
b.insert("a");
b.insert("b");
b.insert("three");
set_difference( a.begin(), a.end(), b.begin(), b.end(), inserter(result, result.begin()));
cout << "Difference" << endl << "-------------" << endl;
for (set<string>::const_iterator i = result.begin(); i != result.end(); ++i) {
cout << *i << endl;
}
result.clear();
set_symmetric_difference(a.begin(), a.end(), b.begin(), b.end(), inserter(result, result.begin()));
cout << "Symmetric Difference" << endl << "-------------" << endl;
for (set<string>::const_iterator i = result.begin(); i != result.end(); ++i) {
cout << *i << endl;
}
return 0;
}
【讨论】:
我想这应该可行。
for( set<string> :: iterator it = a.begin(); it != a.end(); ++it )
{
set<string>:: iterator iter = find( b.begin(), b.end(), *it );
if( iter == b.end() )
{ // ^^^^^^^ Note: find returns b.end() if it does not find anything.
c.insert(*iter)
}
}
【讨论】:
NULL,它返回你传入的“end”迭代器(在本例中为b.end())。
【讨论】: