Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use Insert in Set for Custom Data Type ? C++

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading