[英]Searching for a range [x,y] in a sorted vector in C++ [using lower_bound() and upper_bound() ]
[英]lower and upper_bound on sorted vector of struct
比如說我有:
struct my_stuff{
long my_value;
struct less_than{
bool operator()(const my_stuff &a, const my_stuff &b){
return a.my_value < b.my_value;
};
};
在我的代碼中,我有:
vector<my_stuff> my_vec;
這個向量已經包含了我感興趣的所有對象。然后我根據my_value成員變量對向量進行了排序
sort(my_vec.begin(), my_vec.end(), my_stuff::less_than());
到目前為止一切都很好。 現在,根據成員變量“ my_value”對我的矢量對象進行排序。
我的問題/問題是:如何基於“ my_value”獲得此向量的lower_bound和upper_bound。 例如,如果讓我希望所有對象位於my_value的[low,high]范圍內,則我希望lower_bound指向該bound(low)中的最低對象,而upper_bound指向我的high(高)。
到目前為止,我嘗試過的是...
auto low = lower_bound(myvec.begin()->my_value, my_vec.end()->my_value, val);
對於上限,除了“ upper_bound”而不是“ lower_bound”之外,還有相同的事情。 如何從句法上實現這一目標? 對對象的向量進行排序后,我想做的就是能夠找到特定范圍內的所有對象。 我相信lower_bound和upper_bound是解決此問題的正確方法,但是我對編寫它感到困惑。 感謝您的幫助或指導!
有兩種方法。 您可以構造一個包裝了所需值的my_stuff
實例,並將其傳遞給lower_bound
:
my_stuff test; test.my_value = val;
auto low = std::lower_bound(time_table.begin(), time_table.end(), test,
my_stuff::less_than());
或者,在less_than::operator()
添加幾個重載,將my_stuff
放在一邊,另一邊放在long
的地方。 使用支持異構比較的比較器,您可以編寫
auto low = std::lower_bound(time_table.begin(), time_table.end(), val,
my_stuff::less_than());
如果您實現my_stuff::operator<()
而不是單獨的比較器,則可以進一步避免將my_stuff::less_than()
傳遞給std::lower_bound
(並傳遞給std::sort
my_stuff::operator<()
有三個超載)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.