Consider following snippet:
#include <bits/stdc++.h>
using namespace std;
int main() {
int x=3;
int y=1;
int z=2;
cout<<(&x)<<' '<<(&y)<<' '<<(&z)<<endl;
set<reference_wrapper<int>> a;
a.insert(ref(x));
a.insert(ref(y));
a.insert(ref(z));
for(const auto& i: a) cout<<i<<' '<<endl;
y=10;
for(const auto& i: a) cout<<i<<' ';
return 0;
}
What would happen to underlying container when a property used by container for sorting is modified?
Edit1 : From what I can try by running code, ordering goes wrong but since it was holding a reference, value is correctly updated. So one should be careful when using reference_wrapper inside containers (specially where mutations can cause container to invalidate its assertions)?
std::setare supposed to beconst. As with almost anything there are ways to bypass this restriction but what you get is a broken set.std::setprovides you no non-const access to the elements.std::set::iteratoris a constant iterator. Further note that you are not actually modifying the elements, they areconst, but you modify the objects they refer to. The issue is with the comparator. I am not aware of some formalism that requires that when you doauto x = comp(a,b);, do something (but not insert nor remove elements),auto y = comp(a,b);thatxandymust be the same.#include <bits/stdc++.h>? Block that site. Burn that book. Unfriend that friend. Learn C++ from a good C++ book.