primer C++笔记
其他只读算法
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/d30feb0a4e070e9e565adc47608172d2.png#pic_center)
#include <iostream>
#include <stdlib.h>
#include <vector>
#include <algorithm>
using namespace std;
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 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';
}
#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';
}
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");
}