Re: how do i set the size / reserve of a vector..
On Dec 24, 6:09 am, "Greg" <imut...@hotmail.co.uk> wrote:
How do i set the size / reserve of a vector ?
template < typename T >
class BaseVec : public Vec< T > {
public:
void setsize(const int &sz) { reserve(sz); };
BaseVec(): Vec<T>() { }
};#define MAX_MODS 128
I'm not sure just what "Vec" is , however if you intended std::vector,
then it should look like this:
template < typename T >
class BaseVec : public std::vector< T > {
public:
void setsize(std::size_t sz) //type that reserve really wants--
change quiet scompiler warnings
{
reserve(sz);
};
// compiler generated default constructor fine in this case
};
However, note how the result behaves:
void foo(){
BaseVec<int> myvec ;
assert(myvec.size()==0); //size() from std::vector
myvec.setsize(20);
assert(myvec.size()==0);
assert(myvec.capacity()> ); //capacity() from std::vector
myvec.resize(40); //resize() from std::vector
assert(myvec.resize()==40);
assert(myvec.capacity()>=40); //capacity() from std::vector
std::vector<int> * myvec2 =new BaseVec<int>;
delete myvec2; //illegal C++ code, std:: vector does not
have a virtual destructor
}
"std::vector::reserve(x)" only makes sure that the guts of your vector
is capable of holding x instances of T-- it doesn't actually create
them. std::vector::capacity() will tell you just how many copies of T
your vector will hold without having to reallocate its internals, and
copy all the live instances to the new storage. Recall that std::vector
has the property that the guts are always contiguous. Take note that
std::vector is the only std container that has these functions -- using
them locks you in.
However, size() refer to how many instances of T are actually in the
container. resize() will construct instances of T either by default
constructing them, or by copy constructor using resize(std::size_t , T
const&); The "sequence" containers have these (namely vector list, and
deque) and the corresponding container adapters "stack" and "queue"
On the public inheritance, if your program is small enough or tools
good enough to easily detect the illegal deletion through base class
pointer, then the public inheritance isnt a problem --in fact it solves
more problems than it creates, which is what you want. I use this
design myself, the moral is just be aware of the caveats.
Hope this helps
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]