如何在C++中声明和初始化全局数组?

huangapple go评论72阅读模式
英文:

How to declare and initialize a global array in C++?

问题

在Java中,我可以声明全局数组(在文件范围内),然后在主函数中初始化它们。

在C++中,我尝试了以下代码块:

这次程序告诉我数组的大小确实是N(而不是0)。然而,现在这个向量只在主函数中可用,不是全局的。我能像在Java中那样使向量cows全局吗?

英文:

In Java, I can declare global (within the scope of a file) arrays and then initialize them in the main function.

public static int[] arr;

public static void main(String[] args) {
    arr = new int[N]; // N is possibly given as i/o.
    ...
}

This allows me to have this array is a global variable. Can I do the same thing in C++?

I tried the following code block in C++:

#include <bits/stdc++.h>
using namespace std;

int N;
vector<int> cows(N);

int main() {
	cin >> N;
	
	for (auto& elem : cows) {
		elem = 2;
	}
	cout << cows.size() << '\n';
}

This failed and it told me that the size of my array is 0. However, when I move the initialization of the vector into main, like this:

#include <bits/stdc++.h>
using namespace std;

int N;

int main() {
	cin >> N;
	vector<int> cows(N);

	for (auto& elem : cows) {
		elem = 2;
	}
	cout << cows.size() << '\n';
}

Now, the program gives me that the size of the array is indeed N (and not 0). However, now this vector is only avaiable in main and isn't global. Can I make the vector cows global, like you can do in Java?

答案1

得分: 3

以下是翻译好的内容:

问题在于你的第一个示例中,Ncows 都是全局变量,这意味着 N 将至少被零初始化(由于静态初始化),这反过来意味着 cows 被定义为一个没有元素的向量(即大小为 0 的向量)。

为了解决这个问题,你可以在询问用户大小后使用 std::vector::resize 来调整向量的大小,如下所示:

int N;  // 至少被零初始化(静态初始化)
vector<int> cows(N); // 你可以将这行重写为 vector<int> cows;

int main() {
    cin >> N;

    // 调整向量的大小,传递输入的大小
    cows.resize(N);
    
    for (auto& elem : cows) {
        elem = 2;
    }
    cout << cows.size() << '\n';
}

另一方面,第二种情况可以正常工作,因为你直接创建了一个大小为 N 的向量,其中 N 是由用户提供的大小,不像第一种情况,那里是零初始化的。

英文:

The problem is that in your first example,both N as well as cows are global variables which means that N will be at least zero initialized(due to static initialization) which in turn means that cows is defined to be a vector with no elements(that is, a vector of size 0).

To solve this, you can use std::vector::resize to resize the vector after asking the user the size as shown below:

int N;  //at least zero initialized(static initialization)
vector&lt;int&gt; cows(N); //you can rewrite this as just vector&lt;int&gt; cows;

int main() {
    cin &gt;&gt; N;

    //resize the vector passing the input size 
    cows.resize(N);
    
    for (auto&amp; elem : cows) {
        elem = 2;
    }
    cout &lt;&lt; cows.size() &lt;&lt; &#39;\n&#39;;
}

OTOH the second case works because you directly create a vector of size N where N is the size given by the user unlike the first case where it was zero initialized.

huangapple
  • 本文由 发表于 2023年5月26日 00:10:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76334323.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定