C++ undeclared identifier vector
Solution 1
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);
Solution 2
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.
![Abhishek Jain](https://i.stack.imgur.com/xQDgh.jpg?s=256&g=1)
Abhishek Jain
Updated on July 09, 2022Comments
-
Abhishek Jain almost 2 years
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); }
-
Mike Seymour over 10 yearsThen read this, remove it, and qualify the names properly.
-
Abhishek Jain over 10 years@ MikeSeymour After doing all the changes stated by you,when I run the program, vector subscript exception occurs.Please help.
-
Mike Seymour over 10 years@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.