Hello,
I'm trying to make a custom set that will only keep the highest n entries based on a custom comparator (if there is already a way of doing this with the STL let me know!). Anyway, it works on Windows with Visual Studio 2010, but not on Linux with GCC 4.1.2. My code is as follows:
#include <set>
#include <iostream>
//typedef double T;
template<class T>
bool test_comp(T a, T b){
return a < b; // this is arbitrary to illustrate point
}
template<class T>
class MySet {
private:
std::set<T,bool(*)(T, T)> _set;
size_t maxSize;
public:
MySet(size_t _maxSize, bool(*fpt)(T,T)){
_set = std::set<T,bool(*)(T,T)>(fpt);
maxSize = _maxSize;
}
bool insert(T d){
if(_set.size() == maxSize){
std::set<T,bool(*)(T,T)>::const_iterator it = --_set.rbegin().base();
if(d < *it){
_set.erase(it);
_set.insert(d);
returntrue;
} else {
returnfalse;
}
}
_set.insert(d);
returnfalse;
}
T getOptimal() const {
return *(_set.begin());
}
};
int main(int argc, char ** argv){
//create set with a function pointer comparator
MySet test(3,test_comp);
test.insert(2);
test.insert(3);
test.insert(4);
test.insert(5);
test.insert(6);
test.insert(1);
std::cout << test.getOptimal() << std::endl;
return 0;
}
When this is compiled, the following output is generated:
test.cpp: In member function 'bool MySet<T>::insert(T)':
test.cpp:23: error: expected `;' before 'it'
test.cpp:25: error: 'it' was not declared in this scope
test.cpp: In function 'int main(int, char**)':
test.cpp:45: error: missing template arguments before 'test'
test.cpp:45: error: expected `;' before 'test'
test.cpp:47: error: 'test' was not declared in this scope
If the template<class T> is replaced with typedefdouble T; it compiles fine. Any ideas?
For the second error (in main function)
This is incorrect: MySet test(3,test_comp);
should be MySet<some_type_in_here> test(3,test_comp); as MySet is a template class.