c++ - 将二维 vector 的值设置为 0 的快速方法

标签 c++ vector

给出下面的例子

#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, appends sz - size() default-inserted elements to the sequence.

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].

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/

相关文章:

c++ - 如果使用 remove_if 如何删除 vector 的空单元格

java - 无法在 Vector<Superclass> 中从子类转换为父类(super class)

C++ 默认函数参数

c++ - .c编程如何在客户端和服务器之间建立sip session

c++ - C++ "Identifier not found"问题的非常简单的代码

c++ - 插入和 push_back 指向唯一指针 vector 的指针会产生不同的编译行为?

c++ - 初始化 vector vector

c++ - 将自动分配的 std::vector 转换为动态分配的 std::vector 而无需复制开销

c++ - 如何在带有 std::tr1::weak_ptr 的容器上使用 std::remove?

c++ - Cin.Ignore() 不工作