[Solved] C++ : Unable to read from large txt file [closed]


Your problem is in the merge function:

you exceed the local variable c.

long c[30];

maybe there are more problems, that is the first I notice.

EDIT

Try this: find the differences…

#include <map>
#include <vector>
#include <fstream> 
#include <iostream> 
#include <time.h>
using namespace std;

void merge(vector<long> &,long ,long , long );


void divide(vector<long> &arr,long min, long max){
    long mid;

    if(min<max){
        mid=(min+max)/2;
        if(min != mid) divide(arr,min,mid);
        if(max != mid+1) divide(arr,mid+1,max);
        merge(arr,min,mid,max);
    }
    return;

}

void merge(vector<long> &arr,long min, long mid,long max){
    long i,j,k;
    map<long,long> c; //uses map because the vector not always start from 0
    //other option is to use vector<long> c(max-min) and substruct min when copy to/from it.
    //like this: vector<long> c(1+max-min); //initialize size = max-min+1
    //           c[k-min] = arr[i];
    //           arr[i] = c[i-min];
    i=min,j=mid+1;
    k=min;

    while(i<=mid && j<=max){
        if(arr[i]<arr[j]){
            c[k]=arr[i];
            i++;
            k++;
        }
        else{
            c[k]=arr[j];
            j++;
            k++;
        }
    }
    while(i<=mid){
        c[k]=arr[i];
        i++;
        k++;
    }
    while(j<=max){
        c[k]=arr[j];
        j++;
        k++;
    }

    for(long i=min;i<=max;i++)
        arr[i]=c[i];
}

void create_input(int i){
    srand(time(NULL));
    ofstream fout("sample2.txt");
    while(i--){
        fout<<rand()<<" ";
    }
} 

int main(){

    vector<long> data;
    long tmp;
    long count=0;
    //create random input
    //create_input(31);

    ifstream fin("sample2.txt");

    while(fin >> tmp)
    {
        data.push_back(tmp);
        count++;//count = data.size(); !!
    }
    cout<<"the unsorted array is\n";
    for(long i=0;i<count;i++)
        cout<<i<<"]\t"<<data[i]<<"\n";

    divide(data,0,count-1);//use last index not size

    cout<<"the sorted array is\n";
    for(long i=0;i<count;i++)
        cout<<i<<"]\t"<<data[i]<<"\n";


    return 0;
}

4

solved C++ : Unable to read from large txt file [closed]