如何找到一对中的一对元素?

时间:2017-03-11 05:35:34

标签: c++ algorithm c++11 stl

set<pair<int,int> >s;
pair<int,int>a0 = make_pair(1,10); // pair is kind of range of integer
air<int,int>a1 = make_pair(11,50);
s.insert(a0);
s.insert(a1);

现在我需要一个函数,当我搜索任何位于集合中任何一对范围之间的整数时,该函数返回true。

3 个答案:

答案 0 :(得分:2)

迭代集合并检查整数是否在集合

中的每一对中
bool bet(set<pair<int,int> > s, int integer) 
{
    for (auto it : s)
    {
        if (it.first <= integer && it.second >= integer) 
            return true;
    }
    return false;
}

答案 1 :(得分:1)

如果您想要快速搜索(即优于线性搜索),则应使用interval tree。 std :: set不适合这个问题

答案 2 :(得分:1)

  

现在我需要一个函数,当我搜索任何位于集合中任何一对范围之间的整数时,该函数返回true。

这似乎是std::any_of()

的作品
#include <set>
#include <utility>
#include <iostream>
#include <algorithm>

bool anyRange (std::set<std::pair<int, int>> const & s, int v)
 { return std::any_of(s.cbegin(), s.cend(),
                      [&](std::pair<int, int> const & p)
                       { return (p.first <= v) && (v <= p.second); }); }

int main()
 {
   std::set<std::pair<int, int>> s { {1, 10}, {11, 50} };

   std::cout << anyRange(s, -5) << std::endl; // print 0
   std::cout << anyRange(s, 5)  << std::endl; // print 1
   std::cout << anyRange(s, 25) << std::endl; // print 1
   std::cout << anyRange(s, 75) << std::endl; // print 0
 }