[英]C++ Custom Comparison Functors
I am trying to pass a custom functor into std::map.我正在尝试将自定义函子传递给 std::map。
So, I declare the following functor and the class whose member is a map in a HEADER file.因此,我在 HEADER 文件中声明了以下仿函数和 class,其成员是 map。
class Comp {
bool g;
public:
Comp(bool greater) : g(greater) {}
bool operator()(float lhs, float rhs) const {
if (g) return lhs >= rhs;
return lhs < rhs;
}
};
class OrderBook {
u_char OrderBookType;
std::map<float, std::vector<float*>, Comp> OrderBookData;
public:
OrderBook(u_char);
float best_bid_ask(int);
};
And in a.cpp file, I define the constructor for OrderBook class as follows to initialize the std::map.在 a.cpp 文件中,我如下定义 OrderBook class 的构造函数来初始化 std::map。
OrderBook::OrderBook(u_char bookType) {
OrderBookType = bookType;
OrderBookData(Comp(bookType == 'B'));
}
However, when I try to compile the program, I run into a "type does not provide a call operator" error:但是,当我尝试编译程序时,遇到“类型不提供调用运算符”错误:
error: type 'std::map<float, std::vector<float *>, Comp>' does not provide a call operator
OrderBookData(Comp(bookType == 'B'));
I am very confused as to why I am running into this error.我很困惑为什么会遇到这个错误。
Any help is much appreciated.任何帮助深表感谢。
You need to use initializer list syntax to construct the members:您需要使用初始化列表语法来构造成员:
OrderBook::OrderBook(u_char bookType) :
OrderBookType{bookType},
OrderBookData{Comp{bookType == 'B'}} { }
At the point where you are trying to construct the map, it is already default-constructed.在您尝试构建 map 时,它已经是默认构建的。 The syntax you're using looks like a function call, so the compiler looks for a suitable
operator()
function on the map, but doesn't find it -- hence the error.您使用的语法看起来像 function 调用,因此编译器会在 map 上寻找合适的
operator()
function,因此出现错误 - 但没有找到。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.