c++ - 如何找到对集合中一对之间的元素?

标签 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。

最佳答案

Now I need a function which returns true when I search any integer which lies between range of any pair in the set.

它似乎适用于 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
 }

关于c++ - 如何找到对集合中一对之间的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42731753/

相关文章:

c++ - 以目录作为参数运行 C++ 文件?使用 Bash 代替?

在两组人之间安排面试的算法

python - Fisher Yates Shuffle 错误实现中的顺序偏差

c++ - MinGw标准2011的基本编译

c++ - 创建对象并将其插入 vector 的正确方法是什么?

c++ - 使用 concurrent_unordered_map 时崩溃

c++ - 为什么 (new Foo())->baa() 有效而 new Foo()->baa() 无效?

c++ - llvm jit 编译成二进制

C++ 覆盖成员变量 (std::vector)

java - 在这种情况下用策略模式替换复杂的条件语句是否有意义