Home > Software engineering >  Searching for a non-cost pointer in an STL set using a const argument
Searching for a non-cost pointer in an STL set using a const argument

Time:11-13

I have a set of pointers to a class:

std::set<myclass*> myset

In a function that gets a const myclass* ss argument, I want to search whether myset contains ss:

bool item_in_set( const myclass *ss ) {
  return myset.find( ss ) != myself.end();
}

This fails with an 'argument would lose const qualifier' error. Although it makes sense, I would expect that std::set has a way to search for items using a const qualifier but I can't find anything. To make this work I used:

bool item_in_set( const myclass *ss ) {
  return myset.find( const_cast<myclass*>( ss ) ) != myself.end();
}

This works but is clunky and I'm concerned that I'm missing something.

Is there a better way to do this, or any risks with my approach?

I don't want to change the signature of item_in_set() as it's pretty far in the call stack of other functions with a const myclass* signature (I have simplified the names in this example).

I'm using C 17.

CodePudding user response:

Switching to a transparent comparator fixes this:

std::set<myclass*, std::less<>> myset;

It's a good idea to use it by default for all your sets/maps.

It makes .find() a template, accepting any type comparable with the element type.

For some reason, it doesn't affect some of the functions (such as .at()); for those I'd continue using const_cast.

CodePudding user response:

Wow, really wierd problem.

One workaround is to use std::find(...) although it might affect performance.

    return std::find( myset.begin(), myset.end(), ss ) != myset.end();
  • Related