0

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?
  • This is one of the perils of `#include ` and `using namespace std;`. It pulls a function template `std::count` from the `` header into your file scope. Hence, when you also have `int count;` and refer to it as `count`, this name can't be resolved, it's ambigious. – lubgr Feb 03 '21 at 07:08
  • Due to `using namespace std` your variable is ambiguous with [`std::count`](https://en.cppreference.com/w/cpp/algorithm/count). Also see https://stackoverflow.com/Questions/31816095/Why-Should-I-Not-Include-Bits-Stdc-H. – Alan Birtles Feb 03 '21 at 07:09
  • please explain the case 1 , declaring count not causing any problem . But using it inside a function , giving error – Brijesh joshi Feb 03 '21 at 07:13
  • 1
    declaring isn't a problem, there's no ambiguity, its only when you try to use it the compiler can't decide whether you want to use your global or `std::count` – Alan Birtles Feb 03 '21 at 08:09

0 Answers0