UINT size = 50;
UINT current = 0;
int *array = new int[size];
void add(int a)
{
if(current++ == size)
{
int *temp = new int[size*2];
copyarray(array, temp);
delete[] array;
array = temp;
}
}
extending dynamic memory
hi, I was wondering if there is anyway to extend an allocated array(in c++) without having to copy all the contents from one to the other to save references to the original array from being lost.
eg.
any pointers to the original array will be lost after you create the new array, Is there any way around this?
how about using STL
int main(blabla)
{
std::vector<mypointer*> vec;
mypointer* p = new mypointer;
vec.push_back( p );
return 0;
}
now you can keep on adding without having to think about moving or reservering memory. The vector will resize itself when it needs more memory. Of course if you are planning on doing this in realtime then you should use the reserve method on the vector.
hope this helps,
Peter Wraae Marino
int main(blabla)
{
std::vector<mypointer*> vec;
mypointer* p = new mypointer;
vec.push_back( p );
return 0;
}
now you can keep on adding without having to think about moving or reservering memory. The vector will resize itself when it needs more memory. Of course if you are planning on doing this in realtime then you should use the reserve method on the vector.
hope this helps,
Peter Wraae Marino
Quote:Original post by staticVoid2
any pointers to the original array will be lost after you create the new array, Is there any way around this?
Depends on exactly what the pointers point to.
If they simply point to the array, use a std::vector instead of raw arrays.
If they point into the array, to specific data elements, no. You'll have to use a different data structure if you want those to stay valid.
Quote:Original post by staticVoid2
hi, I was wondering if there is anyway to extend an allocated array(in c++) without having to copy all the contents from one to the other to save references to the original array from being lost.
If you use std::vector<> it takes care of the copying for you. It also helps to reduce the cost of copying by allocating more than you need initially.
Quote:any pointers to the original array will be lost after you create the new array, Is there any way around this?
Use a different data structure, such as a linked list (std::list<>), or use a smart pointer that refers to an index of an existing std::vector<>, something like:
// completely untestedtemplate<typename T>class vec_elem_ptr{public: typedef std::vector<T>::size_type index_type; vec_elem_ptr(std::vector<T> &v, index_type idx) : v_(&v), idx_(idx) { } T &operator* () const { return v_->at(idx_); } // or assert() and [] T *operator-> () const { return &v_->at(idx_); } // ditto // etc ... // operators ++, -- etc would probably make sense here, tooprivate: std::vector<T> *v_; index_type idx_;};// Maybe a partial specialisation for <const T>...
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement