英文:
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
以下是翻译好的内容:
问题在于你的第一个示例中,N
和 cows
都是全局变量,这意味着 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<int> cows(N); //you can rewrite this as just vector<int> cows;
int main() {
cin >> N;
//resize the vector passing the input size
cows.resize(N);
for (auto& elem : cows) {
elem = 2;
}
cout << cows.size() << '\n';
}
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论