Link to home
Start Free TrialLog in
Avatar of klopter
klopter

asked on

Can push_back() and end() be made to be efficient within vectors?

//  This code can be found at:  http://waldo.wi.mit.edu/~kstanley/STL/ex4.cc
//
//  I am not sure whether my set of objects of class Contig (defined
//  below) will require efficient removal.  If not, I would like to
//  avoid the linked list overhead and just store them as a vector.
//  Hence I wrote the following code which uses a common subset of
//  list and vector:  push_back(), end() and erase().
//
//  My hope is that if erase() is sufficiently infrequent (possibly
//  never used) that this will generate efficient vector code.
//  But, if it turns out that I need to use erase(), I can switch to
//  lists effortlessly.
//
//  I look forward to your thoughts on this.  Do you think that
//  this can be made to run efficiently when I use vectors?
//
//  I have compiled this with and without -DUSELISTS on gcc 2.8.1,
//  cxx V6.2-024 and a copy of stlport downloaded within the past week.
//

class Contig {
 public:
};

#ifdef USELISTS
#include <list>
#define STL_TYPE list
#else
#include <vector>
#define STL_TYPE vector
#endif

main(){

  STL_TYPE<Contig> AllContigs;   // STL_TYPE is vector or list

  AllContigs.push_back( Contig() ) ;
  STL_TYPE<Contig>::iterator a = ((AllContigs.end())) ; a--;
 
  AllContigs.push_back( Contig() ) ;
  Contig Ca = *a;

  AllContigs.erase( (a) );
}




Thanks,
  Ken
Avatar of klopter
klopter

ASKER

Is there an STL container class which
will only offer me to intersection of
the vector and list container classes?

Thanks,
  Ken
First of all, what I usually like to do in this case is to make the container a data member of a class that I defined.  I find that gives you the most amount to encapsulation.  Then if I need to change the container, I just change the data member and some of the class's member functions, I don't have to change any of the code that uses the class.  Does that make sense?
ASKER CERTIFIED SOLUTION
Avatar of nietod
nietod

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
If you use container only as a set of objects without care about order you can remove objects by replacing deleted object with object from the end of vector.
If you need ordering use set or multiset with comparison operator based on sequence in which objects were added.

Note about code: after adding to container new element presaved iterator can become invalid.