STL补充--set集合相等判断

一:问题引出

#include <iostream>
#include <map>
#include <set>

using namespace std;

map<Set, int> MapTest;

int main()
{
    set<int> s1;
    set<int> s2 = set<int>();  //这里我们分别建立了两个集合对象
    MapTest[s1] = 1;
    cout << MapTest.count(s2) << endl;    
    if (s1 == s2)
        cout << "666" << endl;

    s1.insert(12);
    cout << MapTest.count(s2) << endl;
    if (s1 == s2)
        cout << "666" << endl;

    system("pause");
    return 0;
}

(一)建立了两个集合对象(不是一个)

    set<int> s1;
    set<int> s2 = set<int>();  //这里我们分别建立了两个集合对象

 

(二)将集合s1放入map中(并未将s2放入map)

    MapTest[s1] = 1;
    cout << MapTest.count(s2) << endl;    

可以发现我们查找s2时在map中会找到,并且个数为1-->即s1。将s1和s2当做一个集合进行查找

(三)我们直接比较s1和s2(发现结果确实是两种相等)

    if (s1 == s2)
        cout << "666" << endl;

(四)我们单独修改s1,之后使用==与s2比较(发现两种不同)

    s1.insert(12);
    if (s1 == s2)  //不会进入
        cout << "666" << endl;  //不会进入

二:源码分析(符号重载)

(一).集合继承于_Tree

class set : public _Tree<_Tset_traits<_Kty, _Pr, _Alloc, false> >

(二)._Tree对==进行了重载,比较方式如下

// _Tree TEMPLATE OPERATORS
template<class _Traits> inline
bool operator==(const _Tree<_Traits>& _Left, const _Tree<_Traits>& _Right) 
{    // test for _Tree equality
return (_Left.size() == _Right.size()
&& equal(_Left.begin(), _Left.end(), _Right.begin()));    //3.对两个树进行比较,从开始到结束,若是元素一致相等,则判定这两个树为相等
}

三:map补充

int main()
{
    set<int> s1;
    set<int> s2 = set<int>();  //这里我们分别建立了两个集合对象
    MapTest[s1] = 1;
    cout << MapTest.count(s2) << endl;    
    if (s1 == s2)
        cout << "666" << endl;

    s1.insert(12);
    cout << MapTest.count(s2) << endl;
if (s1 == s2)
        cout << "666" << endl;

    system("pause");
    return 0;
}
我们会发现这里还是会输出1,因为map中插入s1时是进行了拷贝插入,不是引用。
所以map中存在的那个集合并不是s1,而是原来那个空集合的拷贝对象。
当s1修改时不会影响到map中的那个集合元素,因此我们使用map查找s2时还是会找到。原因如一二分析

 

posted @ 2019-09-10 23:27  山上有风景  阅读(2198)  评论(0编辑  收藏  举报