Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A fast way to set values of a 2d vector to 0

Tags:

c++

vector

Given the following example

#include <iostream>
#include <vector>
#include <algorithm>
#include<iterator>

using namespace std;

template<typename T>
ostream& operator<<(ostream& os, const vector<T>& v){
    copy(v.begin(), v.end(), ostream_iterator<T>(os, "  "));
    return os;
}


int main (){

vector<int>vec;
vector<vector<int>> x(10,vector<int>());
for(int i=0; i< x.size(); i++)
    x[i].resize((rand() % 100 + 1), 10);

for(int i=0; i< x.size(); i++)
    fill(x[i].begin(),x[i].end(),0);

return 0;
}

What would be the fastest way to set the values in the second vector to 0

thnx

like image 495
user8060 Avatar asked Dec 29 '25 13:12

user8060


1 Answers

It is completely unnecessary to fill the inner std::vectors with zeroes, because resize default-inserts new elements into the vectors which value-initializes them. In the case of ints, value-initialization means setting them to 0.


It can be a little difficult to determine this from the standard, so here's the trail (from N4296 - the C++14 draft):

From the definition of resize:

If size() < sz, appends sz - size() default-inserted elements to the sequence.

The definition of default-inserted:

An element of X is default-inserted if it is initialized by evaluation of the expression

allocator_traits<A>::construct(m, p)

where p is the address of the uninitialized storage for the element allocated within X [and m is an allocator of type A].

Definition of allocator_traits<A>::construct:

template <class T, class... Args>
static void construct(Alloc& a, T* p, Args&&... args);

Effects: calls a.construct(p, std::forward<Args>(args)...) if that call is well-formed; otherwise, [...].

From the definition of an allocator:

a.construct(c, args)

Effect: Constructs an object of type C at c

Default: ::new ((void*)c) C(forward<Args>(args)...)

From the definition of the new-expression:

  • If the new-initializer is omitted, [...]

  • Otherwise, the new-initializer is interpreted according to the initialization rules of 8.5 for direct-initialization.

From the definition of direct-initialization:

  • [...]

  • If the initializer is (), the object is value-initialized.

  • [..]

Value-initialization:

  • if T is a (possibly cv-qualified) class type with [...];
  • if T is a (possibly cv-qualified) class type with [...];
  • if T is an array type, then [...];
  • otherwise, the object is zero-initialized.

Zero-initialization:

  • if T is a scalar type (3.9), the object is initialized to the value obtained by converting the integer literal 0 (zero) to T;

  • if [...]

like image 161
Joseph Mansfield Avatar answered Jan 01 '26 03:01

Joseph Mansfield



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!