如何对存储结构体的vector使用lower_bound并按price字段设置比较函数
问题解答
1. 你编写的比较函数存在兼容性问题
原有写法的问题:
- 参数没有加
const限定,不符合STL算法对比较函数不修改入参的要求,部分编译器会直接报错 - 建议改为引用传递避免不必要的结构体拷贝开销
修正后的比较函数如下:
bool compf(const order_book& a, const order_book& b){ return a.price < b.price; }
2. 你当前的lower_bound调用方式存在两处错误
- 没有传入自定义比较函数,默认会调用
order_book的<运算符,你没有重载该运算符会直接编译失败 - 第三个参数是
int类型的价格值,和容器存储的order_book类型不匹配,无法直接比较
3. 正确的实现方式
方式1:使用你定义的比较函数
需要构造一个临时order_book对象作为比较基准,同时将比较函数作为第四个参数传入lower_bound:
long target_price = stol(temp.at(4)); // 用stol转long匹配price字段类型,避免溢出 // 构造临时结构体,仅price字段为目标值即可 order_book temp_book{"", 0, "", 0, target_price}; auto loc = lower_bound(buy_side.begin(), buy_side.end(), temp_book, compf); // 无需判断空值,空容器时lower_bound返回begin(),insert行为和push_back一致 buy_side.insert(loc, order_book{temp.at(0), stoi(temp.at(1)), temp.at(2), stoi(temp.at(3)), target_price});
方式2:使用Lambda简化写法(更推荐)
无需单独定义比较函数,直接在调用时传入Lambda,支持直接用价格值比较,不需要构造临时结构体:
long target_price = stol(temp.at(4)); auto loc = lower_bound(buy_side.begin(), buy_side.end(), target_price, [](const order_book& elem, long price) { return elem.price < price; }); buy_side.insert(loc, order_book{temp.at(0), stoi(temp.at(1)), temp.at(2), stoi(temp.at(3)), target_price});
注意事项
lower_bound要求输入区间已经按照比较函数的规则升序排列,如果你的买盘/卖盘需要按价格降序排列,需要调整比较逻辑:如果是降序排列的买盘,比较函数改为return elem.price > price即可- 你写的空值判断逻辑完全多余,空容器时
lower_bound返回begin(),insert到begin()的行为和push_back完全一致,可以直接删掉冗余的if-else分支
内容的提问来源于stack exchange,提问作者Ninad Pethkar
相关产品推荐
相关产品推荐

