-3
#include <set>
#include <string>
using namespace std;
struct StudInfo{                    //declaration of structure
    string name;
    int id;
};
int compareID(StudInfo a , StudInfo b){          //Compare function as a parameter 
    if(a.id == b.id) return 0;                   //that is being passed to the set s
    if(a.id < b.id) return -1;
    else return 1;
}
int main(){
    set<StudInfo> s(CompareID);
    return 0;

}

Inside the main() scope I am getting this error (error C2065: 'CompareID': undeclared identifier) Although this same code was successfully compiled in the video lecture in which this code was written Please help.

1 Answers1

0

Golden rule of programming: 99.9% of compiler errors are due to you, not the compiler.

Although this same code was successfully compiled in the video lecture in which this code was written

No it didn't!

How do I know that? Well, it's rather simple. First of all, I discount any possibility that the compiler is at fault. That then allows me to concentrate on the source code, and the compiler output.

The solution is simple: replace set<StudInfo> s(CompareID); with set<StudInfo> s(compareID);. Note the case carefully.

Compilation job done.

Then we can move on to your run-time behaviour. Your comparator function is not correctly specified; you need to replace the function with

bool compareID(const StudInfo& a, const StudInfo& b){
    return a.id < b.id;
}

The comparator must return false for all cases where a.id is not less than b.id. Note I'm passing the parameters by const reference to avoid unnecessary string copies.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • Done, until the comparator issue manifests itself at runtime. – juanchopanza Oct 05 '16 at 07:09
  • Doesn't the constructor need a functor instead of a function? Like in http://stackoverflow.com/questions/2620862/using-custom-stdset-comparator ? – Philipp Oct 05 '16 at 07:20
  • You can use a functor if you need require *state*, if you don't then a regular function is sufficient. The cool cats these days use lambdas. – Bathsheba Oct 05 '16 at 07:21