简体   繁体   English

如何在C ++中检查集合是否包含某个范围内的元素

[英]how to check whether a set has element(s) in certain range in C++

I need to check if a std::set contains element/elements in a range. 我需要检查std::set包含范围内的元素/元素。 For example, if the set is a set<int> {1, 2, 4, 7, 8} , and given an int interval [3, 5] (inclusive with both endpoints), I need to know if it has elements in the set. 例如,如果集合是一个set<int> {1, 2, 4, 7, 8} ,并且给定一个int间隔[3, 5] (包括两个端点),我需要知道它是否包含元素集合。 In this case, return true. 在这种情况下,返回true。 But if the interval is [5, 6] , return false. 但如果间隔是[5, 6] ,则返回false。 The interval may be [4, 4] , but not [5, 3] . 间隔可以是[4, 4] ,但不是[5, 3]

Looks like I can use set::lower_bound , but I am not sure whether this is the correct approach. 看起来我可以使用set::lower_bound ,但我不确定这是否是正确的方法。 I also want to keep the complexity as low as possible. 我还希望尽可能降低复杂性。 I believe using lower_bound is logarithmic, correct? 我相信使用lower_bound是对数的,对吗?

You can use lower_bound and upper_bound together. 您可以一起使用lower_boundupper_bound Your example of testing for elements between 3 and 5, inclusive, could be written as follows: 您测试3到5之间(包括3和5)之间元素的示例可以写成如下:

bool contains_elements_in_range = s.lower_bound(3) != s.upper_bound(5);

You can make the range inclusive or exclusive on either end by switching which function you are using ( upper_bound or lower_bound ): 您可以通过切换正在使用的功能( upper_boundlower_bound )使两端的范围包含或排除:

s.upper_bound(2) != s.upper_bound(5); // Tests (2, 5]
s.lower_bound(3) != s.lower_bound(6); // Tests [3, 6)
s.upper_bound(2) != s.lower_bound(6); // Tests (2, 6)

Logarithmic time is the best you can achieve for this, since the set is sorted and you need to find an element in the sorted range, which requires a dichotomic search. 对数时间是您可以实现的最佳时间,因为集合已经排序,您需要在排序范围内找到元素,这需要进行二分法搜索。

If you're certain that you're going to use a std::set , then I agree that its lower_bound method is the way to go. 如果您确定要使用std::set ,那么我同意它的lower_bound方法是lower_bound方法。 As you say, it will have logarithmic time complexity. 如你所说,它将具有对数时间复杂度。

But depending what you're trying to do, your program's overall performance might be better if you use a sorted std::vector and the standalone std::lower_bound algorithm ( std::lower_bound(v.begin(), v.end(), 3) ). 但是根据你要做的事情,如果你使用一个排序的std::vector和独立的std::lower_bound算法( std::lower_bound(v.begin(), v.end(), 3)你的程序的整体性能可能会更好。 std::lower_bound(v.begin(), v.end(), 3) )。 This is also logarithmic, but with a lower constant. 这也是对数,但具有较低的常数。 (The downside, of course, is that inserting elements into a std::vector , and keeping it sorted, is usually much more expensive than inserting elements into a std::set .) (当然,缺点是将元素插入到std::vector中并保持其排序通常比将元素插入到std::set要贵得多。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM