在C ++中是否有用于二进制搜索的库

时间:2014-08-24 19:17:58

标签: c++ search

C ++中是否有预先实现的库可用于二进制搜索等列表中的快速搜索?普通列表是否支持任何类型的查找功能?或者任何类似存在的功能?

我有一个对象列表,我想将它们存储在列表中,但不是重复的元素。我想要注意列表中是否存在新元素并执行适当的操作。

4 个答案:

答案 0 :(得分:3)

std::lower_bound()使用O(log n)比较在任何双向序列中找到合适的位置。由于链接列表不支持随机访问遍历为O(n)。如果您只关心是否有合适的对象,则可以使用std::binary_search()但如果您对定位对象感兴趣,则此算法并不有用。当然,std::lower_bound()std::binary_search()的前提是序列已排序。

答案 1 :(得分:2)

我相信您正在寻找C ++ <algorithm> library。它包含一个名为binary_search的函数。

页面上提供了一个示例,并在此处回显:

// binary_search example
#include <iostream>     // std::cout
#include <algorithm>    // std::binary_search, std::sort
#include <vector>       // std::vector

bool myfunction (int i,int j) { return (i<j); }

int main () {
  int myints[] = {1,2,3,4,5,4,3,2,1};
  std::vector<int> v(myints,myints+9);                         // 1 2 3 4 5 4 3 2 1

  // using default comparison:
  std::sort (v.begin(), v.end());

  std::cout << "looking for a 3... ";
  if (std::binary_search (v.begin(), v.end(), 3))
    std::cout << "found!\n"; else std::cout << "not found.\n";

  // using myfunction as comp:
  std::sort (v.begin(), v.end(), myfunction);

  std::cout << "looking for a 6... ";
  if (std::binary_search (v.begin(), v.end(), 6, myfunction))
    std::cout << "found!\n"; else std::cout << "not found.\n";

  return 0;
}

答案 2 :(得分:1)

如果您正在编写真正的C ++代码,则可以使用算法标准库。

在其中有find function,它授予您查找在指定为参数的元素范围内定义的特定元素。

您可以在同一页面找到一个真实的例子。

答案 3 :(得分:0)

不会采用容器列表来订购元素存储及其直接访问。虽然标准类std::list具有成员函数sort但是使用双向迭代器(std::list具有双向迭代器)而不是随机访问迭代器的搜索不是很有效..

如果您使用某个关联容器,例如std::mapstd::set(如果您需要唯一元素)或std::multimapstd::multiset(如果元素),那会更好可以重复使用。)

如果元素的顺序不重要,那么您可以使用一些标准的无序容器std::unordered_mapstd::unordered_set