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);
}

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);
}

Edited 6 Years Ago by wwsoft: n/a

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);
This question has already been answered. Start a new discussion instead.