【问题标题】:Why only the first element of the array is initialized to -1? while rest of them are 0 [duplicate]为什么只有数组的第一个元素被初始化为-1?而其余的都是0 [重复]
【发布时间】:2019-06-26 18:48:18
【问题描述】:

当我打印它们时,我已将 arr 初始化为 -1,除第一个元素外,每个元素都初始化为 0。

这是一个更大问题的小代码。我只是被打动了

#include <bits/stdc++.h>

using namespace std;

int fibo()
{
    int static arr[100] = {-1};
    for (int i = 0; i < 100; ++i)
    {
        cout << "arr[" << i <<"] : " << arr[i] << endl;
    }
    return -2;
}

int main(void)
{  
    cout << "Result : " << fibo() << endl;
    return 0;
}

【问题讨论】:

  • 最简单的方法是停止使用数组并使用static std::vector&lt;int&gt;,其中初始化语义不像数组那样繁琐。
  • 先生也一样。我不知道为什么它的每个元素都没有初始化为-1。
  • @AshishSiwal 因为他们不应该是。您正在声明一个包含 100 个值的固定数组,但您只为第一个元素指定了一个值。因此,其他元素是值初始化,对于int 意味着0。另一方面,std::vector 有一个将所有元​​素初始化为相同值的构造函数:static vector&lt;int&gt; arr(100, -1);跨度>

标签: c++ arrays static


【解决方案1】:

最简单的解决方案——使用std::vector&lt;int&gt;,所有元素的初始化都以非常简单的形式提供给您(我知道可以使用模板技巧,但 IMO 不需要那种复杂程度在你的代码中)。

例子:

#include <vector>
#include <iostream>

int fibo()
{
    static std::vector<int> arr(100,-1);
    for (int i = 0; i < 100; ++i)
    {
        std::cout << "arr[" << i <<"] : " << arr[i] << "\n";
    }
    return -2;
}

int main(void)
{  
    std::cout << "Result : " << fibo() << "\n";
    return 0;
}

Live Example

【讨论】:

    【解决方案2】:
    #include <bits/stdc++.h>
    
    using namespace std;
    
    int fibo()
    {
        int static arr[100];
        for (int i = 0; i < 100; ++i)
          {
            arr[i] = -1;
          }
        for (int i = 0; i < 100; ++i)
        {
            cout << "arr[" << i <<"] : " << arr[i] << endl;
        }
        return -2;
    }
    
    int main(void)
    {  
        cout << "Result : " << fibo() << endl;
        return 0;
    }
    

    尝试使用此代码

    【讨论】:

    • 我知道这位先生。但是我使用的是静态数组,这样一旦初始化的数组的值就不会在递归过程中一次又一次地初始化。每次调用该函数时,您的代码都会将我的数组初始化为 -1。
    猜你喜欢
    • 2019-10-07
    • 1970-01-01
    • 2015-11-11
    • 2023-02-24
    • 2020-01-15
    • 2013-07-05
    • 2021-07-19
    • 1970-01-01
    • 2020-06-15
    相关资源
    最近更新 更多