set and iterator help

I have trouble understanding the output of the code below. I wrote some notes. Please read them and clarify my misunderstanding of the code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <deque>
#include <list>
#include <algorithm>
#include <set>
#include <queue>
#include <vector>
#include <map>
using namespace std;

int main(){
    int t[]={1,1,2,2,3,3,4,4,5,5};
    list<int>v(t,t+10);  // v contains the same elements as t
    set<int>s1(v.begin(),v.end());  // s1 contains the same as v
    if(s1.count(3)==2){  //  3 3 were erased from s1, hence it now has 
        s1.erase(3);    //   1,1,2,2,4,4,5,5
    }
    for(set<int>::iterator i=s1.begin();i!=s1.end();i++){
        cout << *i<<" ";    // why 1,2,3,4,5 as output? and why not 1,1,2,2,4,4,5,5. Help please.
    }
    return 0;

}
12
13
14
    int t[]={1,1,2,2,3,3,4,4,5,5};
    list<int>v(t,t+10);  // v contains the same elements as t TRUE
    set<int>s1(v.begin(),v.end());  // s1 contains the same as v FALSE 


Sets do not contain copies. In your case, your s1 set will initially contain
{1, 2, 3, 4, 5}

12
13
14
15
16
17
    int t[]={1,1,2,2,3,3,4,4,5,5};
    list<int>v(t,t+10);  // v contains the same elements as t
    set<int>s1(v.begin(),v.end());  // s1 contains {1, 2, 3, 4, 5}
    if(s1.count(3)==2){  //  s1.count(3) equals 1, so...
        s1.erase(3);    //   ... this never happens
    }

thank you.
As an aside, if you replace set<int> on line 14 with multiset<int>, you will get the output you expected.
Topic archived. No new replies allowed.