给出下面的例子
#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;
}
将第二个 vector 中的值设置为 0 的最快方法是什么
谢谢
最佳答案
完全没有必要填充内部std::vector
s 为零,因为 resize
默认将新元素插入值初始化它们的 vector 中。在int
的情况下s,值初始化意味着将它们设置为0。
从标准中确定这一点可能有点困难,所以这是线索(来自 N4296 - C++14 草案):
来自resize
的定义:
If
size() < sz
, appendssz - size()
default-inserted elements to the sequence.
default-inserted
的定义:
An element of
X
is default-inserted if it is initialized by evaluation of the expressionallocator_traits<A>::construct(m, p)
where
p
is the address of the uninitialized storage for the element allocated withinX
[andm
is an allocator of typeA
].
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, [...].
根据分配器的定义:
a.construct(c, args)
Effect: Constructs an object of type C at c
Default:
::new ((void*)c) C(forward<Args>(args)...)
来自new
的定义-表达式:
If the new-initializer is omitted, [...]
Otherwise, the new-initializer is interpreted according to the initialization rules of 8.5 for direct-initialization.
从直接初始化的定义来看:
[...]
If the initializer is (), the object is value-initialized.
[..]
值初始化:
- 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.
零初始化:
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 [...]
关于c++ - 将二维 vector 的值设置为 0 的快速方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29696168/