C++STL算法篇之查找算法(下)

简介: C++STL算法篇之查找算法(下)

统计查找

count(区间查找)

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<functional>
using namespace std;
int main()
{
  vector<int> m = { 1, 1, 1, 1,1 ,2, 4 };
  auto it7 = count(m.begin(), m.end(), 1);
  //统计在vector 容器中1出现的次数
  cout << it7 << endl << endl;
  return 0;
}

count_if(条件查找)

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<functional>
using namespace std;
int main()
{ 
  vector<int> m = { 1, 1, 1, 1,1 ,2, 4 };
  auto it8 = count_if(m.begin(), m.end(), [](int a) {return a > 1; });
  //统计大于1的次数
  cout << it8 << endl;
  return 0;
}

equal(判断是否相等)

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<functional>
#include<iomanip> //流
using namespace std;
int main()
{
  int arr1[] = { 1, 2 };
  int arr2[] = { 1, 2 };
  cout << boolalpha << equal(arr1, arr1 + 2, arr2, arr2 + 2) << endl;
  //用boolalpha的话, 要使用iomanip头文件 ,打印结果是true或者false
  //
  return 0;
}

有序查找

binary_search(二分查找)

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<functional>
#include<iomanip> //流
using namespace std;
int main()
{
  vector<int> mm = { 1, 2, 4 };
  cout << boolalpha << binary_search(mm.begin(), mm.end(), 3);
  return 0;
}

upper_bound(查找第一个大于查找的值)

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<functional>
#include<iomanip> //流
using namespace std;
int main()
{
  vector<int> mm = { 1, 2, 3, 4 };
  //第一个大于2的数
  cout << *upper_bound(mm.begin(), mm.end(), 2);
  return 0;
}

lower_bound (小于查找值)

方法跟上面一样的

equal_range(区间比较,大于等于)

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<functional>
#include<iomanip> //流
using namespace std;
int main()
{
  vector<int> h = { 3, 8, 9, 0, 4, 3 , 4, 10, 100, 6};
  //大于等于
  //first:等于值, second:大于值
  cout << *equal_range(h.begin(), h.end(), 6).first<< endl;
  cout << *equal_range(h.begin(), h.end(), 8).second << endl;
  return 0;
}

注意:以上查找算法应该要做是否能够查找的判定,不能够直接打印,我这里为了方便,省略了这一步


相关文章
|
29天前
|
算法 C++ 容器
C++标准库中copy算法的使用
C++标准库中copy算法的使用
14 1
|
14天前
|
存储 算法 编译器
[C++] STL简介
[C++] STL简介
11 1
|
21天前
|
存储 算法 C++
C++ STL应用宝典:高效处理数据的艺术与实战技巧大揭秘!
【8月更文挑战第22天】C++ STL(标准模板库)是一组高效的数据结构与算法集合,极大提升编程效率与代码可读性。它包括容器、迭代器、算法等组件。例如,统计文本中单词频率可用`std::map`和`std::ifstream`实现;对数据排序及找极值则可通过`std::vector`结合`std::sort`、`std::min/max_element`完成;而快速查找字符串则适合使用`std::set`配合其内置的`find`方法。这些示例展示了STL的强大功能,有助于编写简洁高效的代码。
30 2
|
22天前
|
算法 搜索推荐 C++
c++常见算法
C++中几种常见算法的示例代码,包括查找数组中的最大值、数组倒置以及冒泡排序算法。
14 0
|
27天前
|
安全 编译器 容器
C++STL容器和智能指针
C++STL容器和智能指针
|
29天前
|
算法 C++ 容器
【C++算法】双指针
【C++算法】双指针
|
29天前
|
算法 安全 Linux
|
2月前
|
设计模式 算法 Java
【c++】STL之stack和queue详解
【c++】STL之stack和queue详解
31 1
|
2月前
|
存储 算法 C++
【C++高阶】探索STL的瑰宝 map与set:高效数据结构的奥秘与技巧
【C++高阶】探索STL的瑰宝 map与set:高效数据结构的奥秘与技巧
45 0
|
2月前
|
算法 C++
STL算法大全
以上只是一部分STL算法的简单概述,每一个算法都有其特定的使用场景和规则,具体使用时需要参考相关文档或者教程进行深入理解和学习。
19 0