1

This is a followup of my previous question in which I wanted to know the most efficient way of storing non-duplicate arbitrary data in an std::set.

The answers helpfully pointed out that for custom classes, you'd need to implement operator< (if I understood correctly).

However my particular data type is a vector (in the mathematical sense). What I want to do is store a new vector in the set only if it doesn't already exist. To that end, how can I implement the less-than operator between two vectors? It does not seem to make sense when there are 3 orthogonal dimensions to compare. What strategies can I use to do this?

Community
  • 1
  • 1
Gigi
  • 28,163
  • 29
  • 106
  • 188

1 Answers1

1

std::set can accept any comparison class that implements strict weak comparison as its second template parameter, it doesn't have to be the '<' operator. Just write a comparison that works as '<' would:

struct Compare {

  bool operator( )( const T& left, const T& right ) const {
    if ( left.dimension1 < right.dimension1 ) return true; 
    if ( left.dimension2 < right.dimension2 ) return true; 
    return left.dimension3 < right.dimension3;
  } 

};
Ian
  • 183
  • 1
  • 7
  • This makes sense both from a programming and math perspective. It's clear that the < you are using is only for the purpose of making the set work, and is not meant to imply an ordering on the mathematical vectors with any "nice" mathematical properties. – djechlin Oct 10 '12 at 21:19
  • Yes, but isn't that < nonetheless used to (indirectly) determine equality, and hence uniqueness? Also, how would the code in the given example work together with code that actually uses set? – Gigi Oct 10 '12 at 21:23
  • You can declare the set like this: std::set< T, Compare > item( Compare( ) ); – Ian Oct 10 '12 at 21:35
  • std::set needs more than equality, it needs a well defined ordering. This is why the comparator defaults to the less than operator, if your class can not provide meaningful ordering (by whatever means) then it cannot be used in std::set (or std::map), in which case consider std::unordered_set. – Ian Oct 10 '12 at 21:47