C++ Primer 第11章 泛型算法 学习总结

版权声明:转载请注明出处,如有侵权地方请联系删除 https://blog.csdn.net/qq_21201267/article/details/82990858

标准容器定义的操作比较少,我们需要其他的一些函数来操作容器,比如查找,排序,这些算法不依赖容器类型。

只读算法

1.find函数

find(起始迭代器,终止迭代器,搜索值)
搜索范围不包含终止迭代器位置,函数返回迭代器类型

#include<iostream>
#include<algorithm>
int main()
{
	int ia[7] = {52,13,14,100,66,10,66};
	int search = 66;
	int *position = std::find(ia,ia+7,search);
	std::cout << "the value you want is " << search << (position==ia+7 ? " not found" : " found")
	<< std::endl;
	std::cout << "ia address is " << ia << " address of found value is " << position << std::endl;
}

找到了第一个出现的值
find 找到了第一个出现的搜索值,并返回迭代器(指针)
注意:不加 using namespace std; 则需要写 std::find

2.accumulate函数

需要包含头文件,accumulate(起始迭代器,终止迭代器,初始value);
返回范围内的值和初始value的总和;也可以连接字符串;

#include<iostream>
#include<numeric>
int main()
{
	int ia1[] = {1,2,3,4};
	int sum = std::accumulate(ia1,ia1+3,100);
	std::cout << "sum is " << sum << std::endl;
}

在这里插入图片描述

	string str[] = {"abc","def","ghi","jkl"};
	string strsum = accumulate(str,str+4,string("ok!!!"));
	cout << strsum << endl;

在这里插入图片描述

3.find_first_of 函数

find_first_of(a.起始迭代器,a.终止迭代器,b.起始迭代器,b.终止迭代器)
返回值:迭代器(指向第一个a中的元素,该元素也在b中存在)

	string str[] = {"abc","def","ghi","jkl"};
	string str1[] = {"jkl","haha","abc"};
	string *strp = find_first_of(str,str+4,str1,str1+3);
	cout << *strp << " " << str << " " << strp << endl;

在这里插入图片描述

写容器元素算法

1.fill函数

fill(起始迭代器,终止迭代器,填充值)
使得范围内存在的元素进行写入(填充值)

#include<algorithm>
#include<iostream>
using namespace std;
int main()
{
	int ia[] = {1,2,3,4,5,6};
	fill(ia,ia+5,9);
	for(int i = 0; i != 6;++i)
	{
		cout << ia[i] << " ";
	}
	cout << endl;
	return 0;
}

在这里插入图片描述

2.fill_n函数

fill_n(起始迭代器,计数器n,value)
需要保证要写入的元素存在!!!不然,可能导致严重的错误

	int ib[] = {1,2,3,4,5,6};
	fill_n(ib,5,9);
	for(int i = 0; i != 6;++i)
	{
		cout << ib[i] << " ";
	}

在这里插入图片描述

3.back_inserter插入迭代器

需要iterator头文件
back_inserter(容器对象)在容器尾部添加元素,返回的是一个迭代器

	vector<int> ivec;
	ivec.push_back(1);
	ivec.push_back(2);
	fill_n(back_inserter(ivec),5,3);
	for(vector<int>::iterator it = ivec.begin();it != ivec.end();++it)
	{
		cout << *it << " ";
	}
	cout << endl;

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_21201267/article/details/82990858