JuanPablo
JuanPablo

Reputation: 24754

stl c++: class in a set

I can put a class in a set ? as this case todos.insert(a)

  class arco {
     public:
        arco(int x0, int y0, int z0, int x1, int y1, int z1);
     private:
        std::vector<int> a;
        std::vector<int> b;
        std::set< std::vector<int> > vertices;
  };  
  class arcos {
     public:
        arcos();
        void setArco(arco a); 
     private:
        std::set<arco> todos; 
  };  


  arco::arco(int x0, int y0, int z0, int x1, int y1, int z1){
     std::vector<int> a(3);
     std::vector<int> b(3);
     a[0]=x0;
     a[1]=y0;
     a[2]=z0;
     b[0]=x1;
     b[1]=y1;
     b[2]=z1;
     vertices.insert(a);
     vertices.insert(b);
  }   
  void arcos::setArco(arco a){ 
     todos.insert(a);
  }   

Upvotes: 2

Views: 2621

Answers (3)

John Dibling
John Dibling

Reputation: 101456

Yes, with caveats.

For all STL containers, contained objects are required to be:

  • Copy constructible. You can accomplish this by providing a copy constructor
  • Assignable. You can accomplish this with an assignment operartor operator=(const MyObject&)

In addition, for associative containers, contained objects must be strict-weak comparable. The set itself defines the default implementation of this comparison using less<key_type>, but you can define your own if you wish.

You will often use the default less<key_type> comparison. When you do so, you must provide an bool operator< on your object. There are other, more cumbersome ways to fulfil the strict-weak comparable requirement that do not require you to provide an operator< on your class.

Upvotes: 1

Kiril Kirov
Kiril Kirov

Reputation: 38153

Sure, just overload operator< for class arco or use some comparator

EDIT: One way:

struct compare_arcos
{
  bool operator()( const arco& a1, const arco& a2 ) const
  {
    //..
  }
};

Or


  bool operator<( const arco& a1, const arco& a2 ) const
  {
    //..
  }

If you choose the first way, you sould pass compare_arcos as an argument of the set


Uh, this arcos::arcos(){std::set<arco> todos;} is completely useless.. and wrong

Upvotes: 1

Gene Bushuyev
Gene Bushuyev

Reputation: 5538

You need to define strict weak ordering for your type in order to instantiate set on it. It can be an operator< or a functor.

Edit and clarification. The set declaration is this:

template <
   class Key, 
   class Traits=less<Key>, 
   class Allocator=allocator<Key> 
>
class set;

Key is your type, Traits should be your comparison function, or if you define operator< you can keep default less<Key> you can keep default allocator.

Upvotes: 1

Related Questions