【问题标题】:how can we initialize a vector with all values 0 in C++ [duplicate]我们如何在 C++ 中初始化所有值为 0 的向量 [重复]
【发布时间】:2018-08-29 04:30:10
【问题描述】:

在数组中我们可以做 int arr[100]={0} ,这会将数组中的所有值初始化为 0。 我正在尝试使用类似的矢量 vector <int> v(100)={0} ,但它给出了错误 error: expected ‘,’ or ‘;’ before ‘=’ token。另外,如果我们可以通过 C++ 的“memset”函数来做到这一点,也请告知解决方案。

【问题讨论】:

  • 对数组的常见误解:你不需要{0},人们认为就是使用的值,好像写{5}会构造它们到5。只需编写int arr[100] = {}; 将默认构造它们为0,提供单个值将构造第一个值,其余的构造为0
  • 也许std::vector constructor reference 会有所帮助?

标签: c++ vector stl initialization memset


【解决方案1】:

你可以使用:

std::vector<int> v(100); // 100 is the number of elements.
                         // The elements are initialized with zero values.

您可以通过以下方式明确零值:

std::vector<int> v(100, 0);

您可以使用第二种形式将所有元素初始化为零以外的值。

std::vector<int> v(100, 5); // Creates object with 100 elements.
                            // Each of the elements is initialized to 5

【讨论】:

    猜你喜欢
    • 2012-02-12
    • 2022-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多