primer C++笔记
通用重排操作
#include <iostream>
#include <stdlib.h>
#include <cctype>
#include <string>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
//通用重排操作
//使用前向迭代器的重排算法
namespace ForwardIt
{
//remove(beg, end, val)
//remove_if(beg, end, unaryPred)
//remove_copy(beg, end, dest, val)
//remove_copy_if(beg, end, dest, unaryPerd)
void test01()
{
std::string str1 = "Text with some spaces";
str1.erase(std::remove(str1.begin(), str1.end(), ' '),
str1.end());
std::cout << str1 << '\n';
std::string str2 = "Text\n with\tsome \t whitespaces\n\n";
str2.erase(std::remove_if(str2.begin(),
str2.end(),
[](unsigned char x) {return std::isspace(x); }),
str2.end());
std::cout << str2 << '\n';
//Textwithsomespaces
//Textwithsomewhitespaces
}
//unique(beg, end);
//unique(beg, end, binaryPred);
//unique_copy(beg, end, dest);
//unique_copy_if(beg, end, dest, binaryPred);
void test02()
{
// 移除重复元素
std::vector<int> v { 1,2,3,1,2,3,3,4,5,4,5,6,7 };
std::sort(v.begin(), v.end()); // 1 1 2 2 3 3 3 4 4 5 5 6 7
auto last = std::unique(v.begin(), v.end());
// v 现在保有 {1 2 3 4 5 6 7 x x x x x x} ,其中 x 不确定
v.erase(last, v.end());
for (int i : v)
std::cout << i << " ";
std::cout << "\n";
//1 2 3 4 5 6 7
}
//rotate(beg, end);
//rotate(beg, mid, end, dest);
void test03()
{
std::vector<int> v { 2, 4, 2, 0, 5, 10, 7, 3, 7, 1 };
std::cout << "before sort: ";
for (int n : v)
std::cout << n << ' ';
std::cout << '\n';
// 插入排序
for (auto i = v.begin(); i != v.end(); ++i) {
std::rotate(std::upper_bound(v.begin(), i, *i), i, i + 1);
}
std::cout << "after sort: ";
for (int n : v)
std::cout << n << ' ';
std::cout << '\n';
// 简单地旋转到左侧
std::rotate(v.begin(), v.begin() + 1, v.end());
std::cout << "simple rotate left : ";
for (int n : v)
std::cout << n << ' ';
std::cout << '\n';
// 简单地旋转到右侧
std::rotate(v.rbegin(), v.rbegin() + 1, v.rend());
std::cout << "simple rotate right : ";
for (int n : v)
std::cout << n << ' ';
std::cout << '\n';
/*before sort : 2 4 2 0 5 10 7 3 7 1
after sort : 0 1 2 2 3 4 5 7 7 10
simple rotate left : 1 2 2 3 4 5 7 7 10 0
simple rotate right : 0 1 2 2 3 4 5 7 7 10*/
}
}
//使用双向迭代器的重排算法
namespace BidirIt
{
//reverse(beg, end);
//reverse(beg, end, dest)
void test01()
{
std::vector<int> v{ 1,2,3 };
std::reverse(std::begin(v), std::end(v));
for (auto e : v) std::cout << e;
std::cout << '\n';
int a[] = { 4, 5, 6, 7 };
std::reverse(std::begin(a), std::end(a));
for (auto e : a) std::cout << e;
/*321
7654*/
}
}
//使用随机访问迭代器的重排算法
#include <random>
#include <iterator>
namespace RandomIt
{
/*random_shuffle(beg, end);
random_shuffle(beg, end, rand);
shuffle(beg, end, Uniform_rand);*/
void test01()
{
std::vector<int> v = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(v.begin(), v.end(), g);
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
//可能的输出:
//8 6 10 4 2 3 7 1 9 5
}
}