Initialze array with value

Hi,

I have following problem, I want to pass an array to a function and at one point of the programm I want to delete the whole array, so I thought of using a pointer to the array, like this;

1
2
3
4
5
6
double *buff_arr;
buff_ arr = new double[100];
...
//use of array
...
delete[] buff_arr;


However I want to initialze all elemente with the same value, so is there a possibility to do it directly with the initialization? I know zou can do it with a normal array:

double buff_arr[100] = {1};

or do I need to make a loop to set all the elements to the value.

Furthermore I need to erase the array during run time, as I use it as a buffer array for calculations. So I want to set again all values to 0, at the moment I use a loop to do so, is there another way I can do this?

Thanks in advance!




You need to use a loop, but there are standard algorithms (tamplate functions) that you can call instead of writing the loop yourself:

1
2
buff_arr = new double[100];
std::fill(buff_arr, buff_arr + 100, 1.0);


BTW: Instead of using a plain C-style array, you might be better off using std::vector or boost::array.
Last edited on
Thanks for the answer.

BTW: Instead of using a plain C-style array, you might be better off using std::vector or boost::array.


I have been using std:vector so far, however I couldn't find a command to deallocate the memory used by the vector. There was just a method to erase an element, but as I could read this doesn't mean the memory is cleared. As my vector (or array) is huge, about 4 million elements or even more, and I have several arrays of this size, it is important that I can deallocate the memory.
Furthermore I was told that vectors are supposed to be slower then a C array, as it is a class and so each use of en element is a call to this class. For that reason I finally changed to an array.
vector will probably be very slightly slower than a bare array, but mostly because STL installations typically enable STL debugging by default which adds overhead. Otherwise, because of its ease of use, I would use vector to start with and switch to array only if the added overhead provably is causing a performance problem.

BTW, the only way to cause the vector to shrink its underlying storage buffer is to destroy the object and reconstruct it. This generic function would do the job
(though you might consider writing reconstruct_vector and not making it a template):

1
2
3
4
5
6
7
8
#include <algorithm>

template< typename T >
void reconstruct( T& t ) 
{
    T tmp;
    std::swap( tmp, t );
}


Topic archived. No new replies allowed.