C++ 如何比较两个 std::set?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16182958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to compare two std::set?
提问by Yuushi
I do such comparison of two 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++;
}
}
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?
这是正确的方法吗?或者是比较两组的任何其他(特殊)方式?
回答by Yuushi
Yes, operator==
is correctly defined for all standard containers (exceptthe 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:
是的,operator==
已为所有标准容器(无序容器除外- 基于标准的 23.2.5.2)正确定义,并且通常会进行字典比较。参见此处的示例。相关报价:
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.
检查 lhs 和 rhs 的内容是否相等,即 lhs.size() == rhs.size() 和 lhs 中的每个元素是否在相同位置具有 rhs 中的等效元素。
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
是有序容器,任何具有相同大小和相同元素的集合(假设比较器相同)将必然将它们放在相同的位置,因此比较相等。
回答by WiSaGaN
There are several set operations in C++ standard library header <algorithm>
.
C++ 标准库头文件中有几个集合操作<algorithm>
。
std::set_difference
gives those elements that are in set 1 but not set 2.
std::set_difference
给出那些在集合 1 但不在集合 2 中的元素。
std::set_intersection
gives those elements that are in both sets.
std::set_intersection
给出在两个集合中的那些元素。
std::set_symmetric_difference
gives those elements that appear in one of the sets but not both.
std::set_symmetric_difference
给出出现在其中一个集合中但不出现在两个集合中的那些元素。
std::set_union
gives those elements that are in either set 1 or set 2.
std::set_union
给出那些在集合 1 或集合 2 中的元素。
The algorithms above can also be applied to STL containers other than std::set
, but the containers have to be sorted first (std::set
is sorted by default).
上述算法也可以应用于 STL 容器以外的 STL 容器std::set
,但容器必须先排序(std::set
默认排序)。