954,174 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

how to track objects and put them on a vector ?

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);
}
wwsoft
Light Poster
29 posts since Jan 2010
Reputation Points: 10
Solved Threads: 0
 

You can supply a predicate to the sort template from 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() );
}
Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

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);
}
wwsoft
Light Poster
29 posts since Jan 2010
Reputation Points: 10
Solved Threads: 0
 

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);
dusktreader
Posting Whiz in Training
259 posts since Jan 2010
Reputation Points: 152
Solved Threads: 41
 

Thanks for the help !

wwsoft
Light Poster
29 posts since Jan 2010
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You