Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest, safest way of holding a bunch of const char* in a set?

Tags:

c++

stl

I want to hold a bunch of const char pointers into an std::set container [1]. std::set template requires a comparator functor, and the standard C++ library offers std::less, but its implementation is based on comparing the two keys directly, which is not standard for pointers.

I know I can define my own functor and implement the operator() by casting the pointers to integers and comparing them, but is there a cleaner, 'standard' way of doing it?

Please do not suggest creating std::strings - it is a waste of time and space. The strings are static, so they can be compared for (in)equality based on their address.

1: The pointers are to static strings, so there is no problem with their lifetimes - they won't go away.

like image 693
florin Avatar asked Dec 13 '22 06:12

florin


2 Answers

If you don't want to wrap them in std::strings, you can define a functor class:

struct ConstCharStarComparator
{
  bool operator()(const char *s1, const char *s2) const
  {
    return strcmp(s1, s2) < 0;
  }
};

typedef std::set<const char *, ConstCharStarComparator> stringset_t;
stringset_t myStringSet;
like image 52
Adam Rosenfield Avatar answered Feb 19 '23 00:02

Adam Rosenfield


Just go ahead and use the default ordering which is less<>. The Standard guarantees that less will work even for pointers to different objects:

"For templates greater, less, greater_equal, and less_equal, the specializations for any pointer type yield a total order, even if the built-in operators <, >, <=, >= do not."

The guarantee is there exactly for things like your set<const char*>.

like image 41
fizzer Avatar answered Feb 18 '23 22:02

fizzer