2016-09-18 46 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()`. 
} 
相关问题