hello can I keep track of objects in a list and being able to sort them by there z var ?

do I use pointers ?
how would I do this ?

#include <vector>

vector<sometype> _objects_;

create_object(object_type)
{
    new object_type myobject;
    _objects_.push_back(myobject);
    return _objects_.at(list_end);
}

remove_object(int pos)
{
    delete *_objects_.at(pos);
    _objects_.erase(pos);

}

sort_object_list()
{
    object_list.sort(object.z);
}

Recommended Answers

All 4 Replies

You can supply a predicate to the sort template from <algorithm> that does the comparison:

#include <algorithm>
#include <vector>

void sort_object_list ( std::vector<sometype>& object_list )
{
  struct compare {
    bool operator() ( const sometype& a, const sometype& b )
    {
      return a.z < b.z;
    }
  };

  std::sort ( object_list.begin(), object_list.end(), compare() );
}

so how can I make this accept all object types ?

create_object(object_type)
{
    new object_type myobject;
    _objects_.push_back(myobject);
    return _objects_.at(_objects_.end);
}

so how can I make this accept all object types ?

create_object(object_type)
{
    new object_type myobject;
    _objects_.push_back(myobject);
    return _objects_.at(_objects_.end);
}

As long as your vector will contain homogenous types (i.e. they are all the same). You could use a templated function:

template<class T>
T& create_object( vector<T> objects ){
   T obj;
   objects.push_back( obj );
   return objects.back();
}

Please note that there is no good method for creating a container class to hold heterogenous data in c++. If you were brave, you could create a vector of void pointers, but you would have no way of knowing the type each element.

If you all of the items you need to put in the container are user defined types, then you could have each class inherit from some arbitrary base class, and then you could create a vector of pointers to the base type object:

class Derived1 :  public Base{....}
class Derived2 : public Base{...}
vector<Base*> v;
Derived1 a;
Derived2 b;
v.push_back(&a);
v.push_back(&b);

Thanks for the help !

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.