Question

I have multiset < Class1 > myset; so I create a new object: Class1* c1 = new Class1(); I was expecting to be able to myset.insert(c1) or myset.insert(new Class1()); but none of them work.

class Class1{
 int time;
public:
  CLass1(int t) : time(t) {}
  bool operator<(Class1 &c2) {return time < c2.time;}
}

How is inserting objects different from inserting integers? I was able to insert ints.

Was it helpful?

Solution

In your definition, myset holds Class1 object, while c1 is a pointer to Class1 object. So that's the type problem.

Either you use myset to hold pointer to objects -- multiset<Class1 *> myset, or copy the newly created object into myset -- myset.insert(*c1); delete c1;. Note that container requires object must be copyable and assignable, and should be comparable by implementing operator<.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top