C++笔记 其他只读算法

primer C++笔记

其他只读算法

在这里插入图片描述

#include <iostream>
#include <stdlib.h>
#include <vector>
#include <algorithm>
using namespace std;

//其他只读算法

//for_each(beg, end, unaryOp);
struct Sum
{
	Sum() : sum{ 0 } { }
	void operator()(int n) { sum += n; }
	int sum;
};
void test01()
{
	std::vector<int> nums{ 3, 4, 2, 8, 15, 267 };

	auto print = [](const int& n) { std::cout << " " << n; };

	std::cout << "before:";
	std::for_each(nums.begin(), nums.end(), print);
	std::cout << '\n';

	std::for_each(nums.begin(), nums.end(), [](int &n) { n++; });

	// 对每个数调用 Sum::operator()
	Sum s = std::for_each(nums.begin(), nums.end(), Sum());

	std::cout << "after: ";
	std::for_each(nums.begin(), nums.end(), print);
	std::cout << '\n';
	std::cout << "sum: " << s.sum << '\n';

	//before: 3 4 2 8 15 267
	//after : 4 5 3 9 16 268
	//sum : 305
}


//mismatch(beg1, end1, beg2);
//mismatch(beg1, end1, beg2, binaryPred);
#include <string>
std::string mirror_ends(const std::string& in)
{
	return std::string(in.begin(),
		std::mismatch(in.begin(), in.end(), in.rbegin()).first);
}
void test02()
{
	std::cout << mirror_ends("abXYZba") << '\n'
		<< mirror_ends("abca") << '\n'
		<< mirror_ends("aba") << '\n';

	/*ab
	a
	aba*/
}

//equal(beg1, end1, beg2);
//equal(beg1, end1, beg2, binaryPred);
void test(const std::string& s)
{
	if (std::equal(s.begin(), s.begin() + s.size() / 2, s.rbegin())) {
		std::cout << "\"" << s << "\" is a palindrome\n";
	}
	else {
		std::cout << "\"" << s << "\" is not a palindrome\n";
	}
}
void test03()
{
	test("radar");
	test("hello");

	/*"radar" is a palindrome
	"hello" is not a palindrome*/
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值