// 向算法传递函数(Primer_P344).cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include "pch.h"
#include <iostream>
#include <string>
#include <vector>
#include <functional>
#include <algorithm>
#include <iterator>
using namespace std;
//iterator unique(iterator it_1,iterator it_2);
void elimDups(vector<string>& words) {
sort(words.begin(), words.end()); //字典序排序单词
auto end_unique = unique(words.begin(), words.end()); //去重 返回迭代器
words.erase(end_unique, words.end());
}
void print(vector<string> words) {
for (int i = 0; i < words.size(); i++)
cout << words[i] << " ";
cout << endl;
}
//二元谓词
bool isShorter(const string& s1, const string& s2) {
return s1.size() < s2.size();
}
bool isLen(string s) {
if (s.size() >= 4)
return true;
return false;
}
void insert(vector<string>& word) {
word.push_back("the");
word.push_back("quick");
word.push_back("red");
word.push_back("fox");
word.push_back("jumps");
word.push_back("over");
word.push_back("the");
word.push_back("slow");
word.push_back("red");
word.push_back("turtle");
}
void STABLE_SORT(vector<string> word) {
cout << "原序列:" << endl;
print(word);
cout << "字典序排序并删除重复值后::" << endl;
elimDups(word);
print(word);
cout << "保持相等元素的相对位置不变 按长度递增排序" << endl;
stable_sort(word.begin(), word.end(), isShorter);
print(word);
}
void FIND_IF(vector<string> word) {
cout << "原序列:" << endl;
print(word);
cout << "字典序排序、删除重复值、长度递增:" << endl;
elimDups(word);
stable_sort(word.begin(), word.end(), isShorter);
print(word);
vector<string>::iterator iter = find_if(word.begin(), word.end(), isLen);
cout << "第一个满足find_if条件是: " << *iter << endl;
}
void fenge() {
cout << "***********************************分割线*************************************" << endl;
}
int main()
{
vector<string> word;
insert(word);
STABLE_SORT(word); //测试stable_sort
fenge();
FIND_IF(word); //测试find_if
return 0;
}
std::stable_sort
template <class RandomAccessIterator>
void stable_sort ( RandomAccessIterator first, RandomAccessIterator last );
template <class RandomAccessIterator, class Compare>
void stable_sort ( RandomAccessIterator first, RandomAccessIterator last,
Compare comp )
无返回值
将范围[first,last]中的元素排序为升序,类似sort,但stable_sort保留了具有等效值的元素的相对顺序。
这个等效值 按照第三个参数(谓词)中函数的定义执行后的相等,并一定是完全相等
unique
从[first,last]范围内的每一组等价元素中移除除第一个元素以外的所有元素。
该函数不能更改包含元素范围(即,它不能改变数组的大小或容器):去掉重复通过替换元素的下一个元素,不是复制,和信号的新尺寸缩短范围通过返回一个迭代器的元素应该考虑它的新元素结束。
未被移除的元素的相对顺序被保留
将完全相同的元素逻辑删除(移到后面) 如果想物理删除 用容器的函数erase
find_fi
返回一个迭代器,遍历容器中每个元素,返回第一个 使 find_if第三个参数(一元谓词 ) 为真的位置,若都不满足返回尾迭代器
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool IsOdd (int i) {
return ((i%2)==1);
}
int main () {
vector<int> myvector;
vector<int>::iterator it;
myvector.push_back(10);
myvector.push_back(25);
myvector.push_back(40);
myvector.push_back(55);
it = find_if (myvector.begin(), myvector.end(), IsOdd);
cout << "The first odd value is " << *it << endl;
return 0;
}
上述例子返回第一个奇数