C++STL-ALGORITHM函数

本文介绍了C++标准模板库(STL)中的关键算法,包括foreach遍历元素、generate生成值、sort排序、fill填充、merge合并排序、replace替换元素及count计数等,展示了这些算法如何简化和优化C++编程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在编写c++代码时,有很多常用方法,在stl algorithm中给出了接口,这里简单介绍部分方法。
std::foreach
逐个元素传入函数或类实例,执行相应的操作。

template<class InputIterator, class Function>
  Function for_each(InputIterator first, InputIterator last, Function fn)
{
  while (first!=last) {
    fn (*first);
    ++first;
  }
  return fn;      // or, since C++11: return move(fn);
}
// for_each example
#include <iostream>     // std::cout
#include <algorithm>    // std::for_each
#include <vector>       // std::vector
void addfunction (int &i) {  // function:
  i++;
}
void myfunction (int i) {  // function:
  std::cout << ' ' << i;
}

struct myclass {           // function object type:
  void operator() (int &i) {i++;}
} myobject;

int main () {
  std::vector<int> myvector={10,20,30};
  for_each (myvector.begin(), myvector.end(), addfunction);
  for_each (myvector.begin(), myvector.end(), myobject);

  std::cout << "myvector contains:";
  for_each (myvector.begin(), myvector.end(), myfunction);
  std::cout << '\n';

  return 0;
}

std::generate
逐个调用函数或实例,并将返回值赋值给当前位置。

template <class ForwardIterator, class Generator>
  void generate ( ForwardIterator first, ForwardIterator last, Generator gen )
{
  while (first != last) {
    *first = gen();
    ++first;
  }
}
// generate algorithm example
#include <iostream>     // std::cout
#include <algorithm>    // std::generate
#include <vector>       // std::vector
#include <ctime>        // std::time
#include <cstdlib>      // std::rand, std::srand

// function generator:
int RandomNumber () { return (std::rand()%100); }

// class generator:
struct c_unique {
  int current;
  c_unique() {current=0;}
  int operator()() {return ++current;}
} UniqueNumber;

int main () {
  std::srand ( unsigned ( std::time(0) ) );

  std::vector<int> myvector (8);

  std::generate (myvector.begin(), myvector.end(), RandomNumber);

  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  std::generate (myvector.begin(), myvector.end(), UniqueNumber);

  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';
 
  return 0;
}

std::sort
数组排序,默认为升序。

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

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

struct myclass {
  bool operator() (int i,int j) { return (i<j);}
} myobject;

int main () {
  int myints[] = {32,71,12,45,26,80,53,33};
  std::vector<int> myvector (myints, myints+8);               // 32 71 12 45 26 80 53 33

  // using default comparison (operator <):
  std::sort (myvector.begin(), myvector.begin()+4);           //(12 32 45 71)26 80 53 33

  // using function as comp
  std::sort (myvector.begin()+4, myvector.end(), myfunction); // 12 32 45 71(26 33 53 80)

  // using object as comp
  std::sort (myvector.begin(), myvector.end(), myobject);     //(12 26 32 33 45 53 71 80)

  // print out content:
  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

std::fill
给数组赋值,可指定范围

template <class ForwardIterator, class T>
  void fill (ForwardIterator first, ForwardIterator last, const T& val)
{
  while (first != last) {
    *first = val;
    ++first;
  }
}
// fill algorithm example
#include <iostream>     // std::cout
#include <algorithm>    // std::fill
#include <vector>       // std::vector

int main () {
  std::vector<int> myvector (8);                       // myvector: 0 0 0 0 0 0 0 0

  std::fill (myvector.begin(),myvector.begin()+4,5);   // myvector: 5 5 5 5 0 0 0 0
  std::fill (myvector.begin()+3,myvector.end()-2,8);   // myvector: 5 5 5 8 8 8 0 0

  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

std::merge
合并数组,并排序

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

int main () {
  int first[] = {5,10,15,20,25};
  int second[] = {50,40,30,20,10};
  std::vector<int> v(10);

  std::sort (first,first+5);
  std::sort (second,second+5);
  std::merge (first,first+5,second,second+5,v.begin());

  std::cout << "The resulting vector contains:";
  for (std::vector<int>::iterator it=v.begin(); it!=v.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

std::replace
数组元素替换

// replace algorithm example
#include <iostream>     // std::cout
#include <algorithm>    // std::replace
#include <vector>       // std::vector

int main () {
  int myints[] = { 10, 20, 30, 30, 20, 10, 10, 20 };
  std::vector<int> myvector (myints, myints+8);            // 10 20 30 30 20 10 10 20

  std::replace (myvector.begin(), myvector.end(), 20, 99); // 10 99 30 30 99 10 10 99

  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

std::count
数组中元素出现的次数

int myints[] = {10,20,30,30,20,10,10,20};   // 8 elements
int mycount = std::count (myints, myints+8, 10);

std::find
数组中查找是否存在某元素,返回查找的指针位置。

  // using std::find with array and pointer:
  int myints[] = { 10, 10, 20, 30, 40 };
  int * p;

  p = std::find (myints, myints+4, 10);
  if (p != myints+4)
    std::cout << "Element found in myints: " << *p << '\n';
  else
    std::cout << "Element not found in myints\n";
### C++ STL 中与二分相关的函数 C++ 标准模板库(STL)提供了多个用于实现二分查找的算法,这些算法通常依赖于有序容器中的数据结构。以下是几个常用的二分查找相关函数及其用法: #### 1. `std::binary_search` `std::binary_search` 是一个简单的布尔返回值函数,它用来判断某个特定值是否存在于已排序的范围中。 ```cpp #include <algorithm> #include <vector> #include <iostream> int main() { std::vector<int> vec = {1, 3, 5, 7, 9}; int value_to_find = 5; if (std::binary_search(vec.begin(), vec.end(), value_to_find)) { std::cout << "Value found!" << std::endl; } else { std::cout << "Value not found." << std::endl; } } ``` 此函数仅能确认目标值是否存在,而无法提供其具体位置[^2]。 --- #### 2. `std::lower_bound` 和 `std::upper_bound` 这两个函数分别返回第一个大于等于给定值的位置以及第一个严格大于给定值的位置。它们可以被组合起来计算某范围内重复元素的数量。 ```cpp #include <algorithm> #include <vector> #include <iostream> int main() { std::vector<int> vec = {1, 3, 5, 5, 5, 7, 9}; auto lower_it = std::lower_bound(vec.begin(), vec.end(), 5); auto upper_it = std::upper_bound(vec.begin(), vec.end(), 5); if (lower_it != vec.end()) { std::cout << "Lower bound index: " << std::distance(vec.begin(), lower_it) << std::endl; } if (upper_it != vec.end()) { std::cout << "Upper bound index: " << std::distance(vec.begin(), upper_it) << std::endl; } std::cout << "Count of elements equal to 5: " << std::distance(lower_it, upper_it) << std::endl; } ``` 上述代码展示了如何通过两个迭代器来获取指定数值在序列中的起始和结束索引,并进一步统计该数目的出现次数。 --- #### 3. `std::equal_range` 这个函数结合了 `std::lower_bound` 和 `std::upper_bound` 的功能,一次性返回一对迭代器表示匹配项的区间边界。 ```cpp #include <algorithm> #include <vector> #include <iostream> int main() { std::vector<int> vec = {1, 3, 5, 5, 5, 7, 9}; auto range = std::equal_range(vec.begin(), vec.end(), 5); if (range.first != vec.end()) { std::cout << "Start index: " << std::distance(vec.begin(), range.first) << std::endl; } if (range.second != vec.end()) { std::cout << "End index: " << std::distance(vec.begin(), range.second) << std::endl; } std::cout << "Number of occurrences: " << std::distance(range.first, range.second) << std::endl; } ``` 这段程序说明了利用单次调用即可获得相同效果的操作方法。 --- ### 总结 以上介绍的是 C++ STL 提供的主要几种基于二分查找技术的功能强大的工具集。每种都有各自适用场景,在实际开发过程中可以根据需求灵活选用合适的版本完成任务。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值