如何在给定范围内找到 std::set<pair<int、int> > 中的最大值?

How to find the maximum in std::set< pair<int, int> > in a given range?

本文关键字:int lt gt 最大值 pair set 范围内 std      更新时间:2023-10-16

我有一组对,我想在 l 和 r 之间的对的第二个条目中找到最大数量(包括 l(。

这是集合的样子:myset = [(0,2(,(1,1(,(2,4(,(3,0(,(4,3(]

这是我尝试过的:

#include <iostream>
#include <set>
using namespace std;
#define INPUT1(x)  scanf("%d", &x)
#define INPUT2(x, y)  scanf("%d%d", &x, &y)
#define OUTPUT1(x) printf("%dn", x);
bool cmp(pair<int, int> A, pair<int, int> B) {
    return A.second < B.second;
}
int main(int argc, char const *argv[]) {
    int n;
    INPUT1(n);
    set< pair<int,int> > myset;
    set< pair<int,int> >::iterator it;
    for (int i = 0; i < n; i++) {
        int val;
        INPUT(val);
        myset.insert(make_pair(i, val));
    }
    int l, r;
    INPUT2(l, r);
    int max = std::max_element(myset.begin()+l, myset.begin()+r+1, cmp)->second;
    OUTPUT1(max);
}

这不起作用,但对于 l = 1 和 r = 3,我想要的是 max 等于 4。

我收到以下错误:

invalid operands to binary expression
('iterator' (aka '__tree_const_iterator<std::__1::pair<int, int>, std::__1::__tree_node<std::__1::pair<int, int>, void *> *, long>') and 'int')

max_element返回最大元素的迭代器。更不用说集合的元素是成对的,而不是单个整数。

正确的写法是:

int max = std::max_element(myset.begin()+l, myset.begin()+r+1, cmp)->second;

你不能以这种方式使用 std::max_element。原因是 std::set 提供了双向迭代器,而不是随机访问迭代器,因此禁止使用 myset.begin()+l 之类的东西。

你应该使用这样的东西:

auto mx = std::numeric_limits<int>::min();
auto first = std::cbegin(myset);
std::advance(first, lf);
auto last = std::cbegin(myset);
std::advance(last, rg + 1);
for (auto it = first; it != std::cend(myset) && it != last; ++it) {
    mx = std::max(mx, it->second);
}

如果第一个小于第二个,则比较函数应返回 TRUE。修

bool cmp(pair<int, int> A, pair<int, int> B) {
    return A.second < B.second;
}

仍然可以使用嵌入迭代器的 lambda 来加速此最大值搜索:

int main (int argc, char* argv []) {
  std::pair<int, int> tmp [5] = {
    std::pair<int, int> (0,2),
    std::pair<int, int> (1,1),
    std::pair<int, int> (2,4),
    std::pair<int, int> (3,0),
    std::pair<int, int> (4,3)
  };
  std::set<std::pair<int, int> > s (tmp, tmp+5);
  size_t l (1), r (3);
  auto imax (s.begin ()), end (s.end ()), il (s.begin ()), ir (s.begin ());
  std::advance (il, l);
  std::advance (ir, r+1); 
  auto max ((int)0);
  auto i(il);
  std::for_each (il, ir, [&imax, &i, &max] (const auto& p) {
    if (p.second > max) {
      imax = i;
      max = p.second;
    }
    ++i;
  });
  std::cout << "*imax == (" << imax->first << ", " << imax->second << ")" << std::endl;
  return 0;
}