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
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, appendssz - size()default-inserted elements to the sequence.
The definition of default-inserted:
An element of
Xis default-inserted if it is initialized by evaluation of the expressionallocator_traits<A>::construct(m, p)where
pis the address of the uninitialized storage for the element allocated withinX[andmis an allocator of typeA].
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 [...]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With