C++标准模板库(STL):常用算法

find()

     ---algorithm中的函数

find(start,end,value)

start搜寻的起点,end搜寻的终点,要寻找的value值

  • 容器的表示方法(只有vector没有内置find()函数,其他容器都有,其他容器用自己的find()函数)

find(a.begin(),a.end(),value)

  • 数组的表示方法

find(a,a+length,val)

所有的返回,均是迭代器(容器)或指针(数组),而非是直观感觉上的索引下标。如果在查找范围内不存在,返回a.end(),这里需要注意的是,a.end()不在查找范围内。

我们可以进一步思考,为什么返回的不是索引下标?这是因为索引下标是在数组这种连续存储的数据结构里面常见的,是一种顺序索引;而很多数据结构的存储并非连续的,不能实现顺序索引,为了兼顾所有的数据结构,所以返回的仅仅是指针或是迭代器。

  • 各个容器自己实现的成员函数

vector没有实现find函数,除此之外,常见容器都实现了自己的find函数。

String是这一种顺序存储结构,其find函数返回的是下标索引。set,map,multiset,multimap都不是顺序索引的数据结构,所以返回的是迭代器。

  • 如果元素不在

对于返回迭代器的查找,通过判断find(a.begin(),a.end(),value)==a.end(),来判断元素是否存在

对于string,通过a.find(val)==string::npos判断,string::npos表示string的max_size()。

扫描二维码关注公众号,回复: 3448076 查看本文章

可以参考:https://blog.csdn.net/sinat_34328764/article/details/79946650


sort()

一般使用sort(begin,end,op)可以用于容器和数组,默认是升序,如果要降序则要编写cmp函数

begin和end是迭代器或数组指针,op是排序方式。

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
bool cmp(int a, int b)
{
	return a >b;//降序
}
int main()
{
	vector<int> v{ 1,2,5,9,8,7,2 };
	sort(v.begin(), v.end(),cmp);
	for(auto it = v.begin(); it != v.end(); it++)
	{
		cout << *it << "   ";
        }
	cout << endl;
	return 0;
}

accumulate()累加

accumulate(begin(),end(),t);

t是累加初始值,eg:accumulate(v.begin(),v.end(),0);

猜你喜欢

转载自blog.csdn.net/Lewis_lxc/article/details/82950520