开发者

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

So we have set<string>开发者_Go百科 a and set<string> b and we want to get std::set<string> c which would contain items that would represent a - b (meaning what is left from a if we remove from it all items from b, if b contains more than a or items not present in a we want to keep them alike such simple math with numbers: 5-6 = 0 while 3-2 = 1)


I think you want std::set_difference() from <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;
}


Assuming you mean the difference of the sets:

set_difference

If you mean comparison between the elements, it is not really possible to answer it in a general or simple way. The answer would be pretty specific to your problem, which isn't specified or clear.


This should work, I guess.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜