c++中有二进制搜索的库吗?

Is there any library for binary Search in C++

本文关键字:搜索 二进制 c++      更新时间:2023-10-16

在c++中是否有任何预先实现的库用于在二进制搜索等列表中快速搜索?普通列表是否支持任何类型的查找函数?或者其他类似的函数?

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

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

我相信你正在寻找c++ <algorithm>库。它包含一个名为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;
}

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

其中有find函数,它允许您查找作为参数指定的元素范围中定义的特定元素。

容器列表不用于元素的排序存储和直接访问。尽管标准类std::list有成员函数sort,但是使用双向迭代器(std::list有双向迭代器)而不是随机访问迭代器进行搜索并不是很有效。

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

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