Path: utzoo!mnetor!uunet!husc6!mailrus!umix!umich!mibte!gamma!sabre!faline!scherzo!allegra!alice!shopiro From: shopiro@alice.UUCP Newsgroups: comp.lang.c++ Subject: Re: resizing operator Message-ID: <7708@alice.UUCP> Date: 19 Feb 88 03:44:36 GMT References: <24568@cca.CCA.COM> Organization: AT&T Bell Laboratories, Murray Hill NJ Lines: 51 Summary: it is easy to build custom resizing into vector classes In article <24568@cca.CCA.COM>, alex@cca.UUCP writes: > > One of the language features that I find missing in C++ is some built-in > support for vector allocation resizing, such as a resize operator. Many > of my programs make use of dynamically changing allocations. When they > were written in C, realloc was used. It is possible to specify the memory > allocation function for new and delete, which (presumably) would allow one > to implement a realloc-type function. But it would be a cleaner interface > to have language support, probably like > > resize[count] pointer; > > which would be similar to vector delete. > > Has any thought been given to this area? Am I missing something obvious? Since C++ per se has a rather weak notion of vectors, it would be difficult to provide a general vector resizing operator as part of the language. It is easy, however, for the programmer to write a vector datatype with a resizing operation. For example, you might write code like the following class Int_vec { int* data; int size; public: Int_vec(int s) { data = new int[size = s]; } ~Int_vec() { delete [size] data; } int& operator[](int i) { return data[i]; } // add bounds check s.v.p. void resize(int); }; void Int_vec::resize(int new_size) { int* p = new int[new_size]; for (register int i = min(size, new_size); i--; ) p[i] = data[i]; free [size] data; data = p; size = new_size; } Alternatively, you could supply Int_vec with operator new() and operator delete() with definitions that called malloc() and free(), and then you could use realloc() in Int_vec::resize(). -- Jonathan Shopiro AT&T Bell Laboratories, Murray Hill, NJ 07974 research!shopiro (201) 582-4179