如何比较两个std :: set? [英] how to compare two std::set?

查看:68
本文介绍了如何比较两个std :: set?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对两个 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("\ns1: %d  s2: %d",*it1,*it2);
        it2++;
    }
}

输出:

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

问题:

这是正确的方法吗?还是还有其他(特殊)比较两组的方法?

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

推荐答案

是的, operator == 已为所有标准容器正确定义(除外是基于无序容器的标准的23.2.5.2),通常会进行字典比较.请参见此处.相关报价:

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:

检查lhs和rhs的内容是否相等,即lhs.size()== rhs.size()和lhs中的每个元素在同一位置的rhs中是否具有相等的元素.

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.

由于 std :: set 是有序容器,因此具有相同大小和相同元素(假设比较器相同)的任何集合都必须将它们放在相同的位置,因此将比较相等

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.

这篇关于如何比较两个std :: set?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆