3

I have the following code for quick sort. When I compile the code it shows following errors:

Error C2065: 'vector' :undeclared identifier
Error C2062: type int : unexpected
Error C3861: 'quicksort': identifier not found

#include "iostream"
#include "conio.h"
#include "vector"
void quicksort(vector<int>,int,int);
int partition(vector<int>,int,int);

using namespace std;

int main()
{   vector<int> unsorted;
    int n,x,y;
//cout<<"Initial size: "<<unsorted.size()<<"\n Capacity: "<<unsorted.capacity();
cout<<"Enter the size: ";
cin>>n;
cout<<"Enter the elements in unsorted array: "<<endl;

for(int a=0;a<n;a++)
{
    cin>>x;
        unsorted.push_back(x);
}
for(int b=0;b<n;b++)
{
cout<<unsorted[b]<<"\t";
}


x=1;
y=n;
 quicksort(unsorted,x,y); //quicksort(array,1,array.length)

 for(int m=0;m<n;m++)
 {
 cout<<unsorted[m]<<"\t";
 }
 return 0;
}


int partition(vector<int> given,int p,int r)
{
    int pivot,i,j;
    pivot=given[r];
    i=p-1;
    for(j=p;j<r-1;j++)
    {
        if(given[j]<pivot)
            i++;
        swap(given[i],given[j]);
    }
    swap(given[i+1],given[r]);
    return i+1;

}

void quicksort(vector<int> given,int p,int r)
{   int q;

    if(p<r)

     q= partition(given,p,r);
     quicksort(given,p,q-1);
     quicksort(given,q+1,r);
}
oz123
  • 27,559
  • 27
  • 125
  • 187
Abhishek Jain
  • 445
  • 2
  • 6
  • 19

2 Answers2

13

move : using namespace std; above quicksort declaration

void quicksort(vector<int>,int,int);
int partition(vector<int>,int,int);

using namespace std;

or better dump using namespace std, and change to:

void quicksort(std::vector<int>,int,int);
int partition(std::vector<int>,int,int);
marcinj
  • 48,511
  • 9
  • 79
  • 100
1

vector, like nearly everything in the standard library, is in namespace std; so the name needs to be qualified. You also need to take the vector by reference, otherwise the function will sort a local copy and have no useful effect.

void quicksort(std::vector<int> &, int, int);
               ^^^^^            ^

In its current form, the rest of the code doesn't need to qualify the standard names since using namespace std; dumps everything you need and more into the global namespace. This is a bad idea, since some of these names (such as partition) might clash with names that you want to declare yourself. You should remove the using directive, and qualify the other standard names (like std::cout) that you use.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • @ MikeSeymour After doing all the changes stated by you,when I run the program, vector subscript exception occurs.Please help. – Abhishek Jain Jan 24 '14 at 13:21
  • @AbhishekJain: It means you're accessing the vector with an out-of-range index. Step through the program in your debugger to find out where. – Mike Seymour Jan 24 '14 at 13:26