【 C++基础】algorithm 库常用函数

本文介绍 C++ 的 algorithm 库中常用函数。algorithm是C++标准程序库中的一个头文件,定义了C++ STL标准中的基础性的算法(均为函数模板)。定义了设计用于元素范围的函数集合。任何对象序列的范围可以通过迭代器或指针访问。

<1>序列容器遍历操作

常用参数对照:
frist : 起点,为一个迭代器
last : 终点,为一个迭代器

for_each

函数原型:

template<class InputIterator, class Function>
  Function for_each(InputIterator first, InputIterator last, Function fn)

功能: 遍历序列容器,将区间[fist,last)之内每一个元素传入函数fn,在函数fn内对元素进行操作;

示例:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
//遍历数组vector,修改vector里的所有元素值为5,输出元素
void fn(int &item)
{
	item = 5;
	cout << item << endl; 
}

int main()
{
	int a[] = {1,2,3,4,5,6,7};
	vector<int> v(a,a+7);
	for_each(v.begin(),v.end(),fn);
} 

find

函数原型:

template<class InputIterator, class T>
  InputIterator find (InputIterator first, InputIterator last, const T& val)
{
  while (first!=last) {
    if (*first==val) return first;
    ++first;
  }
  return last;
}

功能: 返回一个迭代器,该迭代器返回等于val的范围内的第一个元素的迭代器。如果找不到这样的元素,则函数返回last迭代器。
示例:

int a[] = {1,2,3,4,5,6,7};
vector<int> v(a,a+7);
vector<int>::iterator it = find(v.begin(),v.end(),5);//*it = 5
it = find(v.begin(),v.end(),9);//*it = 0

find_if

函数原型:

template<class InputIterator, class UnaryPredicate>
  InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred)
{
  while (first!=last) {
    if (pred(*first)) return first;
    ++first;
  }
  return last;
}

功能: 将区间[fist,last)之内每一个元素传入一元判断式:当pred(elem) 返回true时返回第一个达成条件的元素迭代器;

示例:

int a[] = {1,4,6,2,5,3,7};
	vector<int> v(a,a+7);
	vector<int>::iterator it = find_if(v.begin(),v.end(),fun);//*it = 6

equal

函数原型:

template <class InputIterator1, class InputIterator2>
  bool equal ( InputIterator1 first1, InputIterator1 last1, InputIterator2 first2 )
{
  while (first1!=last1) {
    if (!(*first1 == *first2))   // or: if (!pred(*first1,*first2)), for version 2
      return false;
    ++first1; ++first2;
  }
  return true;
}

功能: 比较两个序列的逐个元素是否相等;

count

函数原型:

template <class InputIterator, class T>
  typename iterator_traits<InputIterator>::difference_type
    count (InputIterator first, InputIterator last, const T& val)
{
  typename iterator_traits<InputIterator>::difference_type ret = 0;
  while (first!=last) {
    if (*first == val) ++ret;
    ++first;
  }
  return ret;
}

功能: 返回序列中等于给定值元素的个数;

示例:

int a[] = {1,4,6,4,5,3,7};
	vector<int> v(a,a+7);
	//把所有的三的倍数替换为 8
	replace_if(v.begin(),v.end(),fun,8); //v = [1 4 8 4 5 8 7]

<2> 序列修改操作

swap

函数原型:

template <class T> void swap ( T& a, T& b )
{
  T c(a); a=b; b=c;
}

函数功能:交换a和b

replace

函数原型:

template <class ForwardIterator, class T>
  void replace (ForwardIterator first, ForwardIterator last,
                const T& old_value, const T& new_value)
{
  while (first!=last) {
    if (*first == old_value) *first=new_value;
    ++first;
  }
}

功能: 把序列中等于old_value元素替换为 new_value;

示例:

int a[] = {1,4,6,5,5,3,7};
	vector<int> v(a,a+7);
	replace(v.begin(),v.end(),5,55);//把5替换成55 

replace_if

函数原型:

template < class ForwardIterator, class UnaryPredicate, class T >
  void replace_if (ForwardIterator first, ForwardIterator last,
                   UnaryPredicate pred, const T& new_value)
{
  while (first!=last) {
    if (pred(*first)) *first=new_value;
    ++first;
  }
}

功能: 将区间[fist,last)之内每一个元素传入一元判断式:当pred(elem) 返回true时的元素替换成new_value;

示例代码:

  #include <iostream>  
  #include <algorithm>
  #include <vector>  
  using namespace std;  
  //把小于5的替换为8 
  bool fun(int i)
  {
  	return i < 5;
  }
  int main()  
  { 
  	 int a[] = {1,2,3,4,5,6,7}; 
  	 vector<int> vec(a,a+7);
     replace_if(vec.begin(),vec.end(),fun,8); //vec = [8 8 8 8 5 6 7]
     return 0;
  }

序列排序

sort

函数原型:

template <class RandomAccessIterator>
  void sort (RandomAccessIterator first, RandomAccessIterator last);
template <class RandomAccessIterator, class Compare>
  void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);

函数功能:
两个重载: 第一个对first到last 升序排序
第二个在第一个基础上传入一个传入一元判断式comp为a < b则升序,否则降序
示例:

  bool fun(int a,int b)
  {
  	return a < b; // a < b : vec =  1 2 3 4 5 6 7
  				  // a > b : vec =  7 6 5 4 3 2 1
  }
  int main()  
  { 
  	 int a[] = {1,3,2,4,6,7,5}; 
  	 vector<int> vec(a,a+7);
     sort(vec.begin(),vec.end(),fun); //vec = [1 2 3 4 5 6 7]
     return 0;
  }

排列函数

next_permutation

函数原型:

     bool next_permutation(iterator start,iterator end)

函数功能:
求的是序列当前排列的下一个排列,当当前序列不存在下一个排列时,函数返回false,否则返回true。
注意: next_permutation() 在使用前需要对欲排列数组按升序排序,否则只能找出该序列之后的全排列数。

代码:

  #include <iostream>  
  #include <algorithm>  
  using namespace std;  
  int main()  
  {  
      int num[3]={1,2,3};  
      do  
      {  
          cout<<num[0]<<" "<<num[1]<<" "<<num[2]<<endl;  
     }while(next_permutation(num,num+3));  
     
     return 0;  
 }

输出:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

需要强调的是,next_permutation() 在使用前需要对欲排列数组按升序排序,否则只能找出该序列之后的全排列数。

下面的代码将展示如何使用next_permutation在接收一个数组p之后对数组p的内容进行全排列,其中n代表数组长度:

#include<iostream>
#include<cstdio> 
#include<algorithm>
using namespace std;
int main()
{
	int n,p[10]; 
	
	scanf("%d",&n);
	for(int i = 0;i < n;i ++)
	{
		scanf("%d",&p[i]);
	}
	sort(p,p+n); //事先排序以保证全排列
	do
	{
		for(int i = 0;i < n;i ++)
		{
			printf("%d ",p[i]);//对于排好序的数组,直接输出即为第一个排列
		}
		printf("\n");
	}while(next_permutation(p,p+n));
	
	return 0;
}
  • 26
    点赞
  • 129
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: C++algorithm常用函数包括: 1. sort():对数组或容器进行排序。 2. find():在数组或容器查找指定元素。 3. binary_search():在已排序的数组或容器进行二分查找。 4. reverse():将数组或容器的元素反转。 5. copy():将一个数组或容器的元素复制到另一个数组或容器。 6. unique():去除数组或容器的重复元素。 7. fill():将数组或容器的元素全部赋值为指定值。 8. max()和min():返回数组或容器的最大值和最小值。 9. accumulate():计算数组或容器的元素之和。 10. count():统计数组或容器指定元素的个数。 11. next_permutation()和prev_permutation():生成下一个或上一个排列。 12. random_shuffle():将数组或容器的元素随机打乱。 13. partition():将数组或容器的元素按照指定条件进行分区。 14. stable_sort():对数组或容器进行稳定排序。 15. nth_element():找出数组或容器第n个元素。 以上是C++algorithm常用函数,希望对您有所帮助。 ### 回答2: C语言algorithm提供了许多常用的算法函数。这些函数涵盖了各种排序、搜索、比较等算法,对于多种应用场景的处理都有很大的帮助。 一、排序算法 1. qsort函数 作用:快速排序 使用方式:qsort(void* base, size_t nmemb, size_t size, int (*compar)(const void*, const void*)) 2. sort函数 作用:排序 使用方式:sort(begin, end) 二、查找算法 1. binary_search函数 作用:二分查找 使用方式:binary_search(start, end, value) 2. lower_bound函数 作用:查找第一个大于等于指定值的元素 使用方式:lower_bound(start, end, value) 3. upper_bound函数 作用:查找第一个大于指定值的元素 使用方式:upper_bound(start, end, value) 三、比较算法 1. equal函数 作用:判断两个序列是否相等 使用方式:equal(start1, end1, start2) 2. lexicographical_compare函数 作用:比较两个序列的字典序大小 使用方式:lexicographical_compare(start1, end1, start2, end2) 四、其他常用函数 1. min函数 作用:获取两个值的最小值 使用方式:min(a, b) 2. max函数 作用:获取两个值的最大值 使用方式:max(a, b) 3. swap函数 作用:交换两个变量的值 使用方式:swap(a, b) 总之,在C++algorithm提供的函数很多,可以使用这些函数来快速解决各种算法问题,提高程序效率,减少代码量。 ### 回答3: C的algorithm包含了很多常用函数,这些函数可以帮助我们在编写C程序时更加高效地处理数据。下面是一些C的algorithm常用函数: 1. sort()函数:这个函数可以将一个数组进行排序,可以根据需要自定义排序方式,也可以使用默认的从小到大排序方式。它的使用方法是sort(arr, arr+size)或者sort(arr, arr+size, comparator_function)。 2. binary_search()函数:这个函数可以在一个有序数组查找一个指定元素,如果找到则返回true,否则返回false。它的使用方法是binary_search(arr, arr+size, target)。 3. lower_bound()函数:这个函数可以在一个有序数组查找某个元素第一次出现的位置,如果不存在,则返回大于该元素的最小元素的位置。它的使用方法是lower_bond(arr, arr+size, target)。 4. upper_bound()函数:这个函数可以在一个有序数组查找某个元素最后一次出现的位置的后一个元素的位置,如果不存在,则返回大于该元素的最小元素的位置。它的使用方法是upper_bond(arr, arr+size, target)。 5. next_permutation()函数:这个函数可以获取一个数组的下一个“排列”,即比当前排列大的最小排列。它的使用方法是next_permutation(arr, arr+size)。 6. prev_permutation()函数:这个函数可以获取一个数组的上一个“排列”,即比当前排列小的最大排列。它的使用方法是prev_permutation(arr, arr+size)。 7. max()函数和min()函数:这两个函数可以分别计算一个数组的最大值和最小值。它们的使用方法是max_element(arr, arr+size)和min_element(arr, arr+size)。 8. accumulate()函数:这个函数可以计算一个数组所有元素的和。它的使用方法是accumulate(arr, arr+size, initial_value)。其,initial_value是一个初始值,可以默认为0。 这些C的algorithm常用函数可以方便我们进行数据处理和计算,在实际编程非常有用。需要注意的是,这些函数的使用方法可能会因为C版本的不同而有所不同,因此在使用时需要参考相应的文档。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

流水线程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值