I am getting a size of 1. Shouldn't it be 4? I am inserting the addresses of integers into the sets.
void func(set<int*>& s1, set<int*>& s2, int a) { s1.insert(&a); s2.insert(&a); } int main() { set<int*> s1, s2; int a = 1, b = 2, c = 3, d = 4; func(s1, s2, a); func(s1, s2, b); func(s1, s2, c); func(s1, s2, d); cout<<" s1.size = "<<s1.size()<<" s2.size = "<<s2.size()<<endl; }
&a
inside func
is the address of the local parameter a
, not the address of the original variable (a
, b
, c
or d
), which:
func
;a
is declared (the end of func
here).In your case, since you do nothing but calling func
4 times in a row, the address of this parameter happens to not change, which is why you get a size of 1 (you insert the same pointer 4 times).
This behavior is implementation defined (thanks @Rakete1111) since sets will need to compare invalid pointers.
Accessing the pointed element through s1
or s2
(e.g. **s1.begin()
) is undefined behavior though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With