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); } 62 Answers
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); 1vector, 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.