使用lower_bound查找矩阵行中序列失败问题排查
问题原因分析
查找失败的核心原因是:lower_bound使用的比较规则与矩阵排序时的规则完全不一致,导致查找逻辑错乱。
- 排序依赖的
Criterion函数是自定义规则:先按行的最大值降序排列,最大值相同时再按行的字典序降序排列。 - 但查找时传给
lower_bound的compareRows函数,仅单纯比较行的字典序大小,完全忽略了「最大值优先」的排序优先级,这就导致lower_bound无法在按自定义规则排序的矩阵中定位到正确元素。
修复方案
必须让lower_bound使用和排序时完全相同的比较逻辑,直接将Criterion作为比较函数传入即可——lower_bound要求比较函数返回true时表示目标值应排在当前元素之前,这和Criterion的逻辑(a应排在b前则返回true)完全匹配。
修改后的main函数代码如下:
int main() { vector<vector<int>> matrix = {{1,2,3}, {3,2,1}, {2,2,2}, {1,1,1}}; vector<int> sequence = {1,2,3}; sortRows(matrix); // 替换compareRows为Criterion<int>,与排序规则保持一致 auto it = lower_bound(matrix.begin(), matrix.end(), sequence, Criterion<int>); if (it != matrix.end() && *it == sequence) { int index = it - matrix.begin()+1; cout << "Found at index " << index; } else { cout << "Not found!" << endl; } return 0; }
额外优化建议
- 比较函数的参数当前是传值方式(
vector<Type>),会产生不必要的容器拷贝,建议改为传引用:bool Criterion(const vector<Type>& vec1, const vector<Type>& vec2)和bool compareRows(const vector<Type>& row1, const vector<Type>& row2),提升运行性能。 - 若矩阵规模较大,可在排序前预先缓存每行的最大值,避免排序时反复调用
max_element进行遍历计算。
内容的提问来源于stack exchange,提问作者THE_CRANIUM
相关产品推荐
相关产品推荐

