2016-09-18 39 views
0

我使用下面的比較函數來對我的向量對進行排序。現在如何使用upper_bound對的向量,以pair.second的遞增順序排列,然後pair.first?

bool sortbysec(const pair<long long,long long> &a, 
      const pair<long long,long long> &b) 
{ 
    if(a.second < b.second) 
    { 
     return true; 
    } 
    else if(a.second==b.second) 
    { 
     if(a.first<b.first) 
     { 
      return true; 
     } 
    } 

    return false; 
} 

我想這樣做upper_boundpair.second與給定值。我如何寫它的比較函數,以便我可以得到第一對second = second element,首先應該是最低的?

謝謝。

+0

使用functor類而不是普通函數。這個類也可以包含對完整向量的引用。 –

+0

您也可以使用普通功能。我不明白這個問題。 –

回答

0

你想要std::lower_bound而不是upper_bound。類似這樣的:

auto iter = std::lower_bound(
    your_contaner.begin(), 
    your_contaner.end(), 
    lookup_second, 
    [](const std::pair<long long,long long>& p, long long second) { 
     return p.second < second; 
    } 
); 
if (iter != your_contaner.end() && iter->second == lookup_second) { 
    // `iter` points to an element with given `second` and smallest `first`. 
    // Otherwise, there's no element with given `second`, and `iter` points 
    // to the leftmost larger element, or `end()`. 
} 
相關問題