如何对一对向量使用upper_bound,按对的递增顺序排列.第二,然后结对,第一

How to use upper_bound with a vector of pairs, arranged in increasing order of pair.second, and then pair.first?

本文关键字:顺序 排列 第二 第一 然后 向量 upper bound      更新时间:2023-10-16

我使用下面的比较器函数对我的配对向量进行排序。

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;
}

现在我想用给定的值对pair.secondupper_bound。我怎么写比较函数,这样我就能得到second = second element和first最小的第一对?

谢谢。

您想要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()`.
}