2011-08-25 326 views
3

因此,我们有set<string> aset<string> b,我们希望得到std::set<string> c这将包含将代表a - b(意思是什么,从a离开,如果我们从它b删除所有项目,如果b包含超过a或项目中不存在的项目a我们希望保持他们的数字都这样简单的数学:5-6 = 03-2 = 1如何获取两个std :: set的元素之间的差异<string>?

回答

11

我想你想从<algorithm>std::set_difference()

#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; 
} 
1

这应该工作,我猜。

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) 
    } 
} 
+0

find找不到'NULL',当它找不到元素时,它返回你传入的“end”迭代器(在本例中为'b.end()')。 – Dawson

+0

有人能解释我哪里出错了吗? – Mahesh

+0

@Toolbox - 好的。纠正。 – Mahesh

3

假设你的意思集合的区别:

set_difference

如果你指的是元素之间的比较,这是不是真的有可能来回答一般性或简单的方法。答案将非常具体到你的问题,这是没有指定或明确。