Topic: Q: stc container autoresize increment?
Author: Christopher Eltschka <celtschk@physik.tu-muenchen.de>
Date: 1998/05/20 Raw View
Cristian Georgescu wrote:
>
> Q: stc container autoresize increment?
> --------------------------------------
>
> Is there possible to specify the number of elements that are
> preallocated when a vector (f.i.) is accessed?
>
> Something like:
>
> vector<int> v;
> v[ 0] = 0; // allocate 10 elements
> //...
> v[10] = 10; // allocate 10 more elements
> //...
>
> This can be achieved manually with reserve() but I would like that this
> is done automatically...
Your code is illegal - even if you use reserve. Just that it happens
to work on your compiler.
vector<int> v;
allocates an empty vector, that is, a vector that contains no elements.
v.reserve(10);
reserves memory for (at least) 10 elements, but it still does contain
*no* *single* *element*!
Note that your code could visibly break if you used a class instead of
int, like the following:
class X // not very useful, but similar things happen in real classes
{
int* val;
public:
X(): val(new int) {}
X(int i): val(new int(i)) {}
X(const X& x): val(new int(x.val)) {}
~X() { delete val; }
X& operator=(const X& ) { delete val; val=new int(x.val); return
*this; }
};
vector<X> v;
v.reserve(10);
v[0]=X(0); // and here a segmentation fault (or GPF) is very
probable...
If you want such a "self-expanding vector", you'll have to write it
yourself (probably using vector for implementation).
Alternatively, you could access the vector with a global function
like this:
template<class T> T& access(vector<T> v, int index)
{
while (v.size() < index)
v.insert(v.end(),10,T());
return v[indev];
}
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html ]
Author: Cristian Georgescu <cgeorges@lehman.COM>
Date: 1998/05/19 Raw View
Q: stc container autoresize increment?
--------------------------------------
Is there possible to specify the number of elements that are
preallocated when a vector (f.i.) is accessed?
Something like:
vector<int> v;
v[ 0] = 0; // allocate 10 elements
//...
v[10] = 10; // allocate 10 more elements
//...
This can be achieved manually with reserve() but I would like that this
is done automatically...
--
Cristian Georgescu
_________________________________________________
email: CGeorges@lehman.com
tel: (212) 526-3502
_/ _/_/_/_/ Lehman Brothers
_/ _/ _/ Equity Finance Systems
_/ _/_/_/_/ World Financial Center
_/ _/ _/ 200 Vesey Street
_/_/_/ _/_/_/_/ New York, NY 10285.
_________________________________________________
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html ]