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?