1
我正在尝试编写一个定义std::map
的类。映射的比较器必须是一个函数指针。函数指针可以作为类的构造函数中的参数传递给类。即使定义了变量,变量也没有类类型
下面是我写的代码:
#include <iostream>
#include <map>
#include <string>
#include <functional>
typedef std::function<bool(std::string x, std::string y)> StrComparatorFn;
bool FnComparator(std::string x, std::string y) {
return strtoul(x.c_str(), NULL, 0) < strtoul(y.c_str(), NULL, 0);
}
class MyClass {
public:
MyClass(StrComparatorFn fptr):fn_ptr(fptr){};
void Insert() {
my_map.insert(std::pair<std::string, std::string>("1", "one"));
my_map.insert(std::pair<std::string, std::string>("2", "two"));
my_map.insert(std::pair<std::string, std::string>("10", "ten"));
}
void Display() {
for (auto& it : my_map) {
std::cout << it.first.c_str() << "\t => " << it.second.c_str() << "\n";
}
}
private:
StrComparatorFn fn_ptr;
std::map<std::string, std::string, StrComparatorFn> my_map(StrComparatorFn(fn_ptr));
};
int main() {
MyClass c1(&FnComparator);
c1.Insert();
c1.Display();
}
我得到一个编译错误在Insert
:
error: '((MyClass*)this)->MyClass::my_map' does not have class type
my_map.insert(std::pair<std::string, std::string>("1", "one"));
任何解决这个问题?
非常感谢。奇迹般有效!! – VinK