c++中有二进制搜索的库吗?
Is there any library for binary Search in C++
在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::map
或std::set
(如果您需要唯一的元素)或std::multimap
或std::multiset
(如果元素可以重复)。
如果元素的顺序不重要,那么你可以使用一些标准的无序容器,如std::unordered_map
或std::unordered_set
相关文章:
- 有根的二进制搜索树.保留与其父级的链接
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 二进制搜索树叶数问题
- 为什么二进制搜索在我的测试中不起作用
- 正在尝试重载二进制搜索树分配运算符
- 我的二进制搜索程序只是关闭了
- 二进制搜索的终止点
- 递归二进制搜索与字符串数组
- 测试树是否为二进制搜索树
- 如何二进制搜索结构向量并在适当的索引处插入
- 如果你有一个固定大小的数组,你需要遍历它!n次,使用二进制搜索如何改变时间复杂性
- 字符串的递归二进制搜索-C++
- 使用二进制搜索树中的迭代器对象访问左侧节点
- 二进制搜索树没有匹配的函数调用
- 二进制搜索不适用于特定输出
- 如何在向量上进行二进制搜索以找到具有特定id的元素
- 如何将Z3_ast导出为二进制以及如何搜索函数名称?
- 二进制搜索树不变的标头文件
- 在C++中搜索二进制文件分隔符时出现不正确的偏移量
- 可视化 在 c++ 中读取和搜索二进制文件