Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
137 views
in Technique[技术] by (71.8m points)

c++ - how to compare two std::set?

I do such comparison of two std::set

#include <cstdlib>
#include <cstdio>
using namespace std;

#include <vector>
#include <set>


int main(int argc, char** argv)
{
    int myints1[]= {10,20,30,40,50};
    int myints2[]= {50,40,30,20,10};
    std::set<int> s1 (myints1,myints1+5);
    std::set<int> s2(myints2,myints2+5);
    if(s1==s2){
        printf("sets: true");
    }else printf("sets: false");
    std::set<int>::iterator it2=s2.begin();
    for(std::set<int>::iterator it1=s1.begin();it1!=s1.end();it1++){
                printf("
s1: %d  s2: %d",*it1,*it2);
        it2++;
    }
}

output:

sets: true
s1: 10  s2: 10
s1: 20  s2: 20
s1: 30  s2: 30
s1: 40  s2: 40
s1: 50  s2: 50

Question:

Is this the right way to do it? Or is any other (special) way of comparing two sets?

question from:https://stackoverflow.com/questions/16182958/how-to-compare-two-stdset

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, operator== is correctly defined for all standard containers (except the unordered containers - based on 23.2.5.2 of the standard), and will generally do a lexicographic comparison. See for example here. The relevant quote:

Checks if the contents of lhs and rhs are equal, that is, whether lhs.size() == rhs.size() and each element in lhs has equivalent element in rhs at the same position.

Since std::set is an ordered container, any set with the same size and same elements (given the comparators are the same) will necessarily have them in the same position, hence will compare equal.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...