Zeroing position of a vector to ensure there is no dirt

Asked

Viewed 8,393 times

3

How do I reset the position of an integer type vector, for example, to ensure that there is no "dirt" when allocating the position in memory in C++?

Some language function or an algorithm.

3 answers

1


If you’re gonna use array really, just do this:

std::fill_n(array, 100, 0);

Some compilers may adopt an extra alternative syntax:

int array[100] = {0};

or

int array[100] = {};

or

int array[100] = { [0 ... 99] = 0 };

Test what produces the result in your compiler if you want one of them. But this is outside the standard, so it should be avoided.

If you want to adopt the C way of doing this (I don’t recommend):

int array[100];
memset(array, 0, sizeof(array));

But in C++ the array is not so recommended, prefer:

std::vector<int> vector1(100, 0);

I put in the Github for future reference.

0

It’s a case where I like to use a macro... but at the bottom is a loop:

#define INIT_ARRAY(array,value) {\
    for(s32 i=0; i<lSIZEOF(array);i++){\
        array[i] = value;\
    }\
}

With this I can make INIT_ARRAY passing the array and the value with which I want to initialize.

0

Just clarifying that arrays are different from Vectors!

In C++, the easiest way to correctly reset a vector is using your own method:
You need the Header:

#include <vector>

A vector of int with 5 Elements

std::vector<int> Numbers = { 1, 2, 3, 4, 5 };

Here you safely clean the whole vector created above

Numbers.clear();

For SIMPLE arrays you can use:
Declaring as below I assign the value 0 to all 5 numbers:

int Numbers[5] = {0};

Still in SIMPLE arrays do not do this in Vectors!!! You can assign ZEROS using memset. Correct way to use!

memset(&Numbers, 0, sizeof(Numbers));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.