如何获得两个std::set的元素之间的差异<string>?

How to get difference between elements of two std::set<string>?

本文关键字:lt 何获得 string gt 之间 std 两个 set 元素      更新时间:2023-10-16

我们有set<string> aset<string> b,我们想要得到std::set<string> c,它将包含代表a - b的项目(意思是如果我们从b中删除所有项目,则a中剩下的项目,如果b包含多于aa中不存在的项目,我们希望保持它们类似于这样简单的数学数字:5-6 = 03-2 = 1)

我认为你想从<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;
}

假设您指的是集合之差:

set_difference

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

我想这应该行得通。

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