简体   繁体   中英

Iterator variable behaving strangely in C++

So I am somewhat new to the intricacies of C++ and its memory handling.

I wrote a piece of code in which the iterator in main function is not behaving as i would expect. It is supposed to take n inputs instead it is just exiting midway depending on the values inputted. The mergeSort and merge function works just fine (at least for small arrays with predefined elements) so no need to check that. The main problem is in the main function. Any help would be appreciated.

#include<cstdio>
#include<iostream>
#include<sstream>
using namespace std;

 void merge(long int *a, long int start, long int mid, long int end)
 {
    long int *c=new long int[1000000];
    long int i,ptr1=0,ptr2=0,ptr=0;
    long int length1,length2;
    length1=mid-start+1;
    length2=end-mid;
    while(ptr1<length1 && ptr2<length2){
        if(a[start+ptr1]>a[mid+ptr2+1]){
            c[start+ptr]=a[mid+ptr2+1];
            ptr++;
            ptr2++;
         }
        else if(a[start+ptr1]<=a[mid+ptr2+1]){
            c[start+ptr]=a[start+ptr1];
            ptr++;
            ptr1++;
         }
     }

    while(ptr1<length1){
        c[start+ptr]=a[start+ptr1];
        ptr++;
        ptr1++;
    }
    while(ptr2<length2){
        c[start+ptr]=a[mid+ptr2+1];
        ptr++;
        ptr2++;
    }

    for(i=0;i<ptr; i++)
      a[start+i]=c[start+i];

 }


 void mergeSort(long int *a, long int start, long int end){

    if(start<end){
        long int mid;
        mid=(start+end)/2;
        mergeSort(a, start, mid);
        mergeSort(a,mid+1, end);
        merge(a, start, mid, end);
     }
 }

 /*Problem lies in Main*/

 int main()
 {
    string s;
    int n,i,j;
    long int *a=new long int[1000000]();
    cin >> n;
    for(i=0;i<n;i++){                             /************Loop exiting midway************/
        cin >> s;
        stringstream g(s);
        g >> n;
        a[i]=n;
     }
    mergeSort(a,0,n-1);
    for(j=0; j<5; j++){
        cout << a[j] << "\n";
     }
     return 0;
 }

Forgive me for bad formatting of code.

g >> n; in the loop is the cause. You overwrite n and thus it fails the loop condition midway.

Simply use cin >> a[i]; inside the loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM