I am a beginner in programming and I observed something new while implementing vectors. my first code in vector initialization doesn't work but the second code works perfectly. please explain to me the reason behind it.
code 1:
#include <iostream>
using namespace std;
#include <vector>
vector<long long int>v;
v.reserve(2);
v.push_back(1);
v.push_back(2);
int main(){
cout<<v[0]<<" "<<v[1]<<endl;
}
it outputs error:'v' does not name a type
code 2:
#include <iostream>
using namespace std;
#include <vector>
vector<long long int>v;
int main(){
v.reserve(2);
v.push_back(1);
v.push_back(2);
cout<<v[0]<<" "<<v[1]<<endl;
}
it works perfectly fine, I am focussing on first because it can be useful when we are working on a medium-sized program and it has many functions defined outside main. for example, in the below code push_back
works fine but I'm not able to define size on the front but I want to do it because my vector has large data of 100000
.
to explain what I meant a part of my code looks like below;
#include <iostream>
using namespace std;
#include <vector>
vector<unsigned long long int>v_val;
void MergeSort(long long arr[],long long n){
long long count=0;
if(n==1)
return;
long long U[n/2];long long V[n-n/2];
for(long long i=0;i<n/2;i++){
U[i]=arr[i];
}
for(long long i=0;i<n-n/2;i++){
V[i]=arr[i+n/2];
}
MergeSort(U,n/2);
MergeSort(V,n-n/2);
count+=merge(U,n/2,V,n-n/2,arr,count);
v_val.push_back(count);
}
int main(){
long long test_count=0;
ifstream file_num("pr_as_2.txt");
long long arr_num[100000];
for(long long i=0;i<100000;i++){
file_num>>arr_num[i];
}
unsigned long long int sum_val=0;
MergeSort(arr_num,70000);
for(size_t i=0;i<v_val.size();i++){
sum_val+=v_val[i];
}
cout<<sum_val;
}