mardi 2 février 2021

Unable to use count as global variable in c++ [duplicate]

I was trying to find number of comparisons in quick sort . But when I am using count I am getting error. Here is the code :

#include <bits/stdc++.h>
using namespace std;

int count = 0;
int partition( int * a , int p , int  r)
{
    int pivot = a[r] ;
    int left = p - 1 ;
    
    for(int i = p ; i < r ; ++i)
    {
        if( a[i] < pivot)
        {
            left++;
            int temp = a[left];
            a[left] = a[i];
            a[i] = temp;
        }
        count++; 
    }
    
    left++;
    
    a[r] = a[left];
    a[left] = pivot;
    
    return left;    
}

void QuickSort(int *a , int l , int r )
{
    if( l < r )
    {
        int p = partition(a , l , r);
        
        QuickSort( a , l , p - 1 ) ;
        QuickSort( a , p + 1 , r );
    }
}



int main()
{
    int arr[7] = { 2,5,3,6,8,9,7};
    QuickSort(arr , 0 , 6);

    
    cout << count ; 
        
    return 0;
}

These are the cases :

  1. Just declaring count as global variable . No error everything fine.
  2. After declaring count , using it inside any function , giving error. ( [Error] - reference to count is ambiguous , [Note] - candidates are : int count )
  3. Using any other variable ( I used c ) it works all fine.
  4. Inside the main() or partition() function accessing ::count isn't giving error and working fine. Why all this happening?

Aucun commentaire:

Enregistrer un commentaire