I am getting following error error: invalid conversion from ‘const int*’ to ‘int*’
Following is my program
#include <set>
int main ( int argc, char **argv) {
std::set<int> intSet;
intSet.insert(1);
intSet.insert(2);
intSet.insert(3);
intSet.insert(4);
intSet.insert(5);
int *pAddress = &(*(intSet.find(4)));
}
I want address of the element in the std::set , This code does not give any compilation error with Microsoft compiler but g++ is giving this compilation error.
It is because each element of
std::setis stored asT const, and the implementation has a reason to do so.Since
std::setcontains exactly a single copy of a value. It has to make it immutable, otherwise, one can change it’s value to something which already exists in the set.Even if the elements were mutable, you would not be able the change the value, because
std::set::findis aconstmember function, and therefore in this functionintSetis immutable and effectively each elements would become immutable as well, including the iterator which it returns, and through which you may change the value at the call-site.The only want to take the address is this:
Don’t use
const_castthough,