0
class Game()
{
 void add(set<Velocity> & v); 
}
class Velocity()
{
private:
  // Member Variables 
public:
   // Constructors and methods 
}

void Game::add(set<Velocity> &velocities)
{
   Velocity v;

   v.setVelocity(); 
   v.setSource();
   velocities.insert(v); 
}

As you can see I have a custom class called Game and it has a public method called Add which adds a velocity object to the set. When the insert(v) code executes it throws me an error: invalid operands to binary expression ('const Velocity' and 'const Velocity') {return __x < __y;}

I am not sure how to fix this, I would appreciate any help or suggestions. Thanks a bunch.

Sulav Dahal
  • 129
  • 3
  • 10
  • 1
    Items in a set must be `<`-comparable. Write a `operator <` for `Velocity`. – tkausl May 19 '22 at 05:20
  • I would appreciate it a lot if you were able to provide an example. Thanks. – Sulav Dahal May 19 '22 at 05:28
  • 1
    Does this answer your question? [std::set.insert won't compile with custom class](https://stackoverflow.com/questions/15913857/stdset-insert-wont-compile-with-custom-class). Dupe2 [Cant insert to std::map (G++)](https://stackoverflow.com/questions/15868776/cant-insert-to-stdmap-g). Dupe3 [problems with c++ set container](https://stackoverflow.com/questions/14784620/problems-with-c-set-container) – Jason May 19 '22 at 05:30

1 Answers1

0

In std::set...

sorting is done using the key comparison function...

You need to look toward something like this:

bool operator<(const Velocity&, const Velocity&);

class Velocity {
friend bool operator<(const Velocity&, const Velocity&);
private:
    unsigned velocity_value;
    // ...
};

bool operator<(const Velocity& a, const Velocity& b)
{
    return a.velocity_value < b.velocity_value;
}

Note, however that in this example, there won't be possible to have two different elements of type Velocity with the same velocity_value, since...

std::set is an associative container that contains a sorted set of unique objects of type Key

If you need to add all the supplied Velocity objects in an instance of the Game, you may need to reconsider the choice of the container, or some other mean of comparison.

rawrex
  • 4,044
  • 2
  • 8
  • 24