Shibli
Shibli

Reputation: 6149

Initialize vector of structures

Let's I have

struct Vector {

    float i,j,k;
}

I want to zero all elements of vec declared below (i,j,k=0)

std::vector <Vector> vec;
vec.resize(num,0);

I don't want to use reserve() and then push_back() zeroes one by one. Another thing is, after succesfully initializing vec, I want to set all members of vec to zero again after it is manipulated. Is there something like memset for vectors?

EDIT: I compared all of the methods in Mike Seymour's and Xeo's answers and as a result size_t size = vec.size(); vec.clear(); vec.resize(size); is the fastest if they are repeated frequently in a loop.

Upvotes: 3

Views: 7619

Answers (3)

Mike Seymour
Mike Seymour

Reputation: 254471

That's very simple:

vec.resize(num);

or initialise it with the required size:

std::vector<Vector> vec(num);

Both the constructor and resize will fill new elements with value-initialised objects. A value-initialised object of a type with no default constructor (such as your Vector) will have all numeric members initialised to zero.

To reset everything to zero, either

size_t size = vec.size();
vec.clear();
vec.resize(size);

or:

std::fill(vec.begin(), vec.end(), Vector());

or, less efficiently but with a strong exception guarantee:

std::vector<Vector>(vec.size()).swap(vec);

Upvotes: 7

Xeo
Xeo

Reputation: 131799

You can just use memset, so long your Vector is a POD type:

std::vector<Vector> v(num, 0); // inital fill
// do stuff
memset(&v[0], 0, sizeof(Vector) * v.size());

Though the C++ version would be with std::fill

#include <algorithm>

std::fill(v.begin(), v.end(), 0);

Upvotes: 1

thiton
thiton

Reputation: 36049

C++ way of setting all current elements to 0:

 std::fill( vec.begin(), vec.end(), 0 );

Or, alternatively, to re-initialize to a given size:

 vec.clear();
 vec.resize(num, 0);

This might not be as performant as memset, but good enough for 99% of the cases.

Upvotes: 1

Related Questions