Appleshell
Appleshell

Reputation: 7388

inserting object into set fails

The following class is present:

class Actor {
public:

    float xpos{0};
    float ypos{0};

    Actor(float x, float y);
    ~Actor();
};

In the a static function of a management class, I want to create such an actor and insert it into a set:

class ActorManager {
private:
    ActorManager();
    static std::set<Actor> actors;
public:
    static void addActor(float x, float y);
}

Definition:

std::set<Actor> ActorManager::actors = std::set<Actor>();

void ActorManager::addActor(float x, float y) {
    Actor actor(x, y);
    actors.insert(actor); // <--
}

With the marked line present, actors.insert, the compilation fails. The error states:

/usr/lib/c++/v1/__functional_base:56:21: Invalid operands to binary expression ('const Actor' and 'const Actor')

What am I missing here?

Upvotes: 0

Views: 384

Answers (2)

Liu Qiankun
Liu Qiankun

Reputation: 1

bool operator <(const Actor& p1, const Actor& p2){
bool result=false;
if (p1.x<p2.x) 
{
result=true;
}
else if (p1.x==p2.x&&p1.y<p2.y){
result=true;
}
return result;

}

//this is the correct way of overloading < operator

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272517

You need to overload operator< in order to use your class with std::set (it needs this in order to sort the elements).

Upvotes: 3

Related Questions