-1

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;
}
def __init__
  • 1,092
  • 6
  • 17

1 Answers1

1

You might be looking for something like

vector<long long int>v {1,2};

Using a list initialization

or

void MergeSort(std::vector<long long>& arr[],long long n){
    long long count=0;
    if(n==1)
        return;
    std::vector<long long> U(arr.begin(), arr.begin()+n/2);
    std::vector<long long> V(arr.begin()++(n-(n/2)), arr.end());
    MergeSort(U,n/2);
    MergeSort(V,n-n/2);
    count+=merge(U,n/2,V,n-n/2,arr,count); <--- need to be fixed too
    v_val.push_back(count);
}

This is not effective due to the many allocations, instead a vector should be allocated at start and be passed as parameter to be reused by the merge.

Also the following is a compiler extension and not part of C++.

long long U[n/2];
Surt
  • 15,501
  • 3
  • 23
  • 39
  • Thank you so much sir, actually, my main doubt was [this question](https://stackoverflow.com/questions/68053605/optimising-count-of-inversioni-e-for-ij-aiaj-for-a-large-array?noredirect=1#comment120283657_68053605) will request you to have a look. – def __init__ Jun 20 '21 at 13:25