泛型算法

// 泛型算法.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include "pch.h"
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <numeric>
#include <string>
using namespace std;

bool mypredicate(int i, int j) {
	return (i == j);
}

int main()
{
	int a[10] = {0,1,2,3,4,5,6,7,8,9};	//1 2 3 4 5 6 7 0 0
	int* beg = begin(a);		//返回首元素指针
	int* ends = end(a);			//尾元素下一元素指针  数组本身大小
	cout << "*beg = " << *beg << endl;
//	cout << *ends << endl;		//不能对尾后指针进行 解引用和 递增操作
	int n = ends - beg;			//数组元素的数量
	
	int val = 10;				//待查找的值
	int* result = find(begin(a), end(a), val); //返回指向第一个与val相等元素的指针 或者迭代器
	if (result == end(a))		//查找失败 返回尾后指针
		cout << "YES" << endl;
	else
		cout << "NO" << endl;
	
	int sum = accumulate(begin(a), end(a), 0); //计算[first,last)内的和 第三个参数是初值
	cout << "sum = " << sum << endl;

	vector<string> vec;
	vec.push_back("hello");
	vec.push_back("world");
	string cat = accumulate(vec.cbegin(), vec.cend(), string("")); //cbegin()返回consr iterator

	int b[9] = { 1,2,3,4,5,6,7,8,9 };
	bool isEqual = equal(cbegin(b), cend(b),a+1);//判断b与a的开头到结尾是否完全相等
	cout << "isEqual = " << isEqual << endl;
	a[3] = 0;
	isEqual = equal(cbegin(b), cend(b), cbegin(a));
	cout << "isEqual = " << isEqual << endl;



	vector<int> v;	//空向量
	fill_n(back_inserter(v),10,2);
	auto it = back_inserter(v);	//得到插入迭代器  
	*it = 3;		//相当于v.push_back

	return 0;
}

equal

将范围 [first1,last)  中的元素与从first2开始的范围中的元素进行比较,如果认为两个范围中的元素相等,则返回true。
通过对每一对对应的元素应用==比较运算符或模板参数comp(用于第二个版本)对元素进行比较。

template <class InputIterator1, class InputIterator2>
  bool equal ( InputIterator1 first1, InputIterator1 last1,
               InputIterator2 first2 );

template <class InputIterator1, class InputIterator2, class BinaryPredicate>
  bool equal ( InputIterator1 first1, InputIterator1 last1,
               InputIterator2 first2, BinaryPredicate pred );

如果范围[first1,last1]中的所有元素与从first2开始的范围中的元素相等,则为true,否则为false。 

上述equal是以第一序列为准的  只要第一序列的范围中所有元素与第二序列开头元素往后的都一一对应 那么返回true

二序列的长度 >= 一序列的长度 否则一定是false

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值