![](/img/trans.png)
[英]How to to pass iterators to the std::lower_bound() comparison function?
[英]std::lower_bound on std::vector with reverse iterators yields a wrong result
最近我發現需要計算超出給定間隔的元素。
例如,如果我有一個有序矢量{10,20,30}和另一個有序矢量{15,25},其邊界定義了間隔。 我想數'10'和'30'(只有20在范圍內)。 為此,我使用std :: vector和std :: lower_bound,一次向前掃描向量,一次向后掃描。
代碼如下所示:
int t[] = { 15, 25 };
int c[] = { 10, 20, 30 };
std::vector<int> tt(t, t + 2);
std::vector<int> cc(c, c + 3);
auto lower = std::lower_bound(cc.begin(), cc.end(), tt.front(), [](int a, int b){ return a < b; });
auto upper = std::lower_bound(cc.rbegin(), cc.rend(), tt.back(), [](int a, int b){ return a > b; });
size_t beforeCount = lower - cc.begin();
size_t afterCount = upper - cc.rbegin();
我希望'lower'和'upper'都指向同一個元素:20。
我花了一些時間在這上面,有沒有人在這看到問題? 我真的很想用STL。
謝謝,Alex
我認為你在迭代器的差異和迭代器指向的值之間感到困惑。
你的程序完全按照你的想法行事, 在這里查看 。
beforeCount
和afterCount
都等於1.它們是迭代器,而不是任何vector元素的值,它們只是指向向量中值的指針。
要打印相應的元素,只需執行以下操作:
std::cout << cc[beforeCount] << std::endl;
std::cout << cc[afterCount] << std::endl;
輸出:
20
20
注意:
您可以在沒有中間數組的情況下初始化矢量:
std::vector<int> tt { 15, 25 };
std::vector<int> cc { 10, 20, 30 } ;
我發現有時很難推斷出反向迭代器。 您可以避免使用它們如下:
auto first = std::lower_bound(cc.begin(), cc.end(), tt.front());
auto second = std::upper_bound(first, cc.end(), tt.back());
size_t beforeCount = first - cc.begin();
size_t afterCount = cc.end() - second;
這與equal_range
非常相似,所以實際上我們可以按如下方式重寫它(盡管在過去使用非標准比較器的非標准實現的MSVC上可能會很麻煩):
typedef std::pair<int, int> Pr;
struct Cmp {
bool operator()(int x, const Pr &y) { return x < y.first; }
bool operator()(const Pr &x, int y) { return x.second < y; }
};
auto pr = std::equal_range(cc.begin(), cc.end(), Pr(15, 25), Cmp());
size_t beforeCount = pr.first - cc.begin();
size_t afterCount = cc.end() - pr.second;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.