Just for practice purpose I write a generic template class which do sorts for a given comparison function.
#include <vector>
#include <iostream>
#include <fstream>
#include "Student.h"
using namespace std;
template <class T, class F>
class myVec {
public:
myVec(vector<T> a);
void sort();
private:
vector<T> w;
int size;
};
template<class T, class F>
myVec<T,F>::myVec(vector<T> a){
w = a;
size = a.size();
}
template<class T, class F>
void myVec<T,F>::sort(){
for(int i=0; i<size; i++){
for(int j=i+1; j<size; j++){
if(F(w.get(i), w.get(j))>0){
iter_swap(w.begin()+i-1, w.begin()+j-1);
}
}
}
}
int cmpStudent(Student stu1, Student stu2){
int score1 = stu1.getScore();
int score2 = stu2.getScore();
if(score1 == score2) return 0;
if(score1<score2) return -1;
return 1;
}
int main(){
typedef int(*fn)(Student, Student);
vector<Student> students;
string fileName = "mydata.data";
ifstream ifs;
ifs.open(fileName.c_str());
string name;
int score;
while(ifs>>name>>score){
Student student(name,score);
students.insert(students.end(), student);
}
myVec<Student, fn> myvec(students);
}
IT works well.
But if I put myVec as a header file and myVec.cpp. include "myVec.h", then the compiler report error on
myVec<Student, fn> myvec(students);
IT bothers me for a long time, why it works when I put all the materials in main