Re: Passing other types to std::set::erase().
On Jun 24, 4:51 am, jasonc <jason.cipri...@gmail.com> wrote:
On Jun 23, 10:36 pm, joseph cook <joec...@gmail.com> wrote:
On Jun 23, 10:09 pm, JC <jason.cipri...@gmail.com> wrote:
I have a class where each instance has a unique ID
associated with it, like this <snip>
Instances are equivalent if their IDs are equivalent.
I am storing these in an std::set<Data>. I'd like to be
able to erase elements from the set given only an ID, that
std::set<Data> somedata = ...;
ID id = ...;
Is there a way I can erase elements from the set by ID
without constructing dummy Data instances, and without
using some other container type instead?
If you define operator==(ID&), then you can accomplish your
goal. Given your description, these seems like it would
provide appropriate semantics as well.
Thanks for your reply. An == operator makes sense in general;
however, this still doesn't solve the problem, as
std::set<Data>::erase(const Data&) takes a Data parameter, not
an ID parameter, so compilation would still fail with an error
along the lines of "no match for somedata.erase(ID)".
Also, AFAIK, doesn't set always use operator< for comparisons
rather than operator== (operator<(ID&) doesn't solve the
You're right on both counts.
In the end, your problem comes down to getting the set to find
the element, given just the idea. This is exactly what std::map
was designed for---if you need to find an element using an
object of a different type as key, you should be using std::map,
and not std::set.
If you're not doing a lot of insertions, you might also consider
using a sorted std::vector, and std::lower_bound---this function
does allow for a "key" with a different type.
James Kanze (GABI Software) email:email@example.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34