高效的C ++数据结构,用于搜索整数值集合中的间隔

时间:2014-12-10 10:59:43

标签: c++ algorithm data-structures

我正在寻找一种数据结构(和C ++实现),它允许(有效地)搜索在给定间隔内具有整数值的所有元素。示例:说集合包含:

3,4,5,7,11,13,17,20,21

现在我想在[5,19]中设置此集合中的所有元素。所以答案应该是5,7,11,13,17

对于我的使用,平凡搜索不是一个选项,因为元素的数量很大(几百万个元素),我不得不经常进行搜索。有什么建议吗?

2 个答案:

答案 0 :(得分:4)

为此,您通常使用std::set,这是一个有序集,其顶部有一个搜索树(至少是一个可能的实现)。

要获取查询间隔中的元素,请找到指向您要查找的第一个和最后一个元素的两个迭代器。这是算法std::lower_boundupper_bound的一个用例,将两个区间限制视为包含:[x,y]。 (如果你想要结束排他性,最后也要使用lower_bound。)

这些算法在集合大小上具有对数复杂度:O(log n)

请注意,如果在应用这些操作之前对其进行排序,也可以使用std::vector。这在某些情况下可能是有利的,但如果您总是想要对元素进行排序,请使用std::set,因为它会自动为您执行。

Live demo

#include <set>
#include <algorithm>
#include <iostream>

int main()
{
    // Your set (Note that these numbers don't have to be given in order):
    std::set<int> s = { 3,4,5,7,11,13,17,20,21 };

    // Your query:
    int x = 5;
    int y = 19;

    // The iterators:
    auto lower = std::lower_bound(s.begin(), s.end(), x);
    auto upper = std::upper_bound(s.begin(), s.end(), y);

    // Iterating over them:
    for (auto it = lower; it != upper; ++it) {
        // Do something with *it, or just print *it:
        std::cout << *it << '\n';
    }
}

输出:

5
7
11
13
17

答案 1 :(得分:0)

要在您提到的时间间隔内进行搜索,细分树是最佳选择。在竞争性编程中,有几个问题基于这种数据结构。

这里可以找到一个这样的实现: http://www.sanfoundry.com/cpp-program-implement-segement-tree/

您可能需要修改代码以适合您的问题,但基本实现仍然相同。