一:問題引出
#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時還是會找到。原因如一二分析