How to get a reference of an element in a set in C++?

But it returns an error, because *it has a type of const Movie (and the function returns Movie& ). But then how to get that element in a way I can change it? A pointer would also be ok, anything that would make it possible to change the element afterwards. movies.find(*it) also returns an iterator to a const Movie , so it also doesn't work when I try to return *(movies.find(*it)) .

asked Mar 5, 2012 at 23:16 9,215 7 7 gold badges 37 37 silver badges 52 52 bronze badges You cannot legally get a non-const reference to an element of a std::set<> . Commented Mar 5, 2012 at 23:18 I hope you don't plan to change this element once it is stored in std::set Commented Mar 5, 2012 at 23:23

Yeah, I planned on changing it. I wanted that set to act like a database (just a temporary one, of course). I tried implementing the "database" with writing and reading from files on disk, but files are too complicated for me in C++, so I chose this approach.

Commented Mar 5, 2012 at 23:29 Commented Mar 5, 2012 at 23:31 That cleared things for me, thanks. Post it as an answer so I can accept it. Commented Mar 5, 2012 at 23:36

2 Answers 2

You can return a const reference, and make the methods for setting the rating const, and declare the member variables you have to change to be mutable. but that's probably not a good idea. mutable members are really intended for things that aren't logically part of the classes 'value'.

You're probably best off not using a std::set. Sets are a special purpose container that makes certain guarantees with pretty narrow uses. Here's an article that talks about what std::set is good for, and it outlines four conditions that should hold before you decide to use one:

When all of those conditions hold then std::set may be a good option. Otherwise, you may well be best off using a vector (probably wrapped in a class that provides a set-like interface).