C++ Generic Algorithm
1 Overview
Generic algorithms are located in algorithm, numeric and other header files
Read-only algorithm:
accumulate(beg,end,start)
count(beg,end,n)
vector<int> ve{1,2,3,4,4,5,6,43,2,1,23,4};
auto beg=ve.cbegin();
auto end=ve.cend();
int sum=accumulate(beg,end,0);
cout<<sum<<endl;
cout<<count(beg,end,4)<<endl;
Write container algorithm:
Algorithm does not check write operations
fill(beg,end,s): write s in the range of [beg,end);
fill_n(beg,n,s)
vector<int> ve{1,2,3,4,4,5,6,43,2,1,23,4};
auto beg=ve.begin();
auto end=ve.end();
fill(beg,end,2);
for(int i:ve){
cout<<to_string(i)+" ";
}
cout<<endl;
vector<int> ve{1,2,3,4,4,5,6,43,2,1,23,4};
auto beg=ve.begin();
auto end=ve.end();
fill_n(beg,5,2);
for(int i:ve){
cout<<to_string(i)+" ";
}
cout<<endl;
If the above n is too large, it will cause memory overflow
back_insert: insert the iterator, get the iterator bound to the container pointing to the insertion position
The following method will not overflow the memory.
vector<int> ve{1,2,3,4,4,5,6,43,2,1,23,4};
auto beg=ve.begin();
auto end=ve.end();
auto it=back_inserter(ve);
int i=0;
fill_n(it,10,4);
for(int i:ve){
cout<<to_string(i)+" ";
}
cout<<endl;
Copy algorithm
copy(begin(a1),end(a1),a2)
Copy array
int a1[]={1,2,3,4,5};
int a2[5];
copy(begin(a1),end(a1),a2);
for (int i = 0; i < 5; ++i) {
cout<<a2[i]<<endl;
}
replace(beg,end,oldValue,newValue):
Replace the old value in the iterator range with the new value. Regular expressions are not supported
vector<string> ve{"aa","bb","cc","dd","ee","dd","cc","bb","aa"};
auto beg=ve.begin();
auto end=ve.end();
replace(beg,end,"aa","xx");
for(auto s:ve){
cout<<s<<endl;
}
replace_copy(beg,end,back_inserter(veCopy),“aa”,“xx”):
Without changing the value of the original container, copy the changed value to another container.
vector<string> ve{"aa","bb","cc","dd","ee","dd","cc","bb","aa"};
vector<string> veCopy;
auto beg=ve.begin();
auto end=ve.end();
replace_copy(beg,end,back_inserter(veCopy),"aa","xx");
for(auto s:veCopy){
cout<<s<<" ";
}
cout<<endl;
for(auto s:ve){
cout<<s<<" ";
}
cout<<endl;
2. Arithmetic of reloading container
unique(words.begin(),words.end()):
Rearrange the elements in the iterator range, save each element only once, and return a position after the last unique element;
#include<algorithm>
#include<numeric>
using namespace std;
void elimDups(vector<string> &);
int main() {
vector<string> ve={"the","quick","fox","jumps","over","the","slow","red","turtle"};
elimDups(ve);
for(string s:ve){
cout<<s<<endl;
}
}
void elimDups(vector<string> &words){
sort(words.begin(),words.end());
auto end_unique=unique(words.begin(),words.end());
words.erase(end_unique,words.end());
}
3. Customized operation
sort(iterator, iterator, pred expression),
Pass in a function as the basis for sorting
#include <iostream>
#include <string>
#include <vector>
#include<algorithm>
#include<numeric>
using namespace std;
void elimDups(vector<string> &);
int main() {
vector<string> ve={"the","quick","fox","jumps","over","the","slow","red","turtle"};
sort(ve.begin(),ve.end(),[](const string &s1,const string& s2){return s1.size()<s2.size();});
for(string s:ve){
cout<<s<<endl;
}
}
find_if(ve.begin(),ve.end(),[sz](const string &s){return s.size()>sz;})
The find_if below finds the first value that matches the lambda expression and uses the captured value.
#include <iostream>
#include <string>
#include <vector>
#include<algorithm>
#include<numeric>
using namespace std;
void elimDups(vector<string> &);
int main() {
vector<string> ve={"the","quick","fox","jumps","over","the","slow","red","turtle"};
int sz=4;
auto w=find_if(ve.begin(),ve.end(),[sz](const string &s){return s.size()>sz;});
cout<<*w<<endl;
/*for(string s:ve){
cout<<s<<endl;
}*/
}
for_each(ve.begin(),ve.end(),[](const string &s){cout<<s<<" ";})
for_each performs the parameters in the lambda expression on the parameters in the iterator range.
#include <iostream>
#include <string>
#include <vector>
#include<algorithm>
#include<numeric>
using namespace std;
void elimDups(vector<string> &);
int main() {
vector<string> ve={"the","quick","fox","jumps","over","the","slow","red","turtle"};
int sz=4;
for_each(ve.begin(),ve.end(),[](const string &s){cout<<s<<" ";});
}
biggest(vector<string> &,vector::size_type)
Arrange the containers from smallest to largest in length, and words of the same length are in lexicographical order.
void biggest(vector<string> &words,vector<string>::size_type sz){
elimDups(words);
stable_sort(words.begin(),words.end(),[](const string &a,const string &b){return a.size()<b.size();});
auto wc=find_if(words.begin(),words.end(),[sz](const string &a){return a.size()>=sz;});
auto count=words.end()-wc;
cout<<count<<" "<<"words"<<endl;
for_each(wc,words.end(),[](const string &s){cout<<s<<" ";});
cout<<endl;
}
void elimDups(vector<string> &words){
sort(words.begin(),words.end());
auto end_unique=unique(words.begin(),words.end());
words.erase(end_unique,words.end());
}
Implicit capture
count_if(ve.begin(),ve.end(),[=](const string &s){return s.size()>4;})
Find a string with a length greater than 4 in the range of the iterator, = is the wording of implicit capture, means copy, & means reference
#include <iostream>
#include <string>
#include <vector>
#include<algorithm>
#include<numeric>
using namespace std;
void elimDups(vector<string> &);
void biggest(vector<string> &,vector<string>::size_type);
int main() {
vector<string>::size_type sz=4;
vector<string> ve={"the","quick","fox","jumps","over","the","slow","red","turtle"};
auto n=count_if(ve.begin(),ve.end(),[=](const string &s){return s.size()>4;});
cout<<n<<endl;
}
auto check_sz=bind(check_size,_1,sz);
_1In the namespace placeholder, it means that the first parameter of the function check_size is bound to sz
Use the bind () function to bind functions and parameters
#include <functional>
using namespace std;
void elimDups(vector<string> &);
bool check_size(const string &a,string::size_type sz);
void biggest(vector<string> &,vector<string>::size_type);
using namespace placeholders;
int main() {
vector<string>::size_type sz=4;
vector<string> ve={"the","quick","fox","jumps","over","the","slow","red","turtle"};
auto check_sz=bind(check_size,_1,sz);
auto n=count_if(ve.begin(),ve.end(),check_sz);
cout<<n<<endl;
}
bool check_size(const string &a,string::size_type sz){
return a.size()>sz;
}
auto isSmaller=bind(compared,_2,_1);
cout<<compared(3,1)<<endl;
cout<<isSmaller(3,1)<<endl;
4. Stream iterator
istream_iterator<int> gets data from the input stream, Int_eof marks the end of the stream
#include <iostream>
#include <string>
#include <vector>
#include <list>
#include <regex>
#include <algorithm>
#include <numeric>
using namespace std;
int main() {
istream_iterator<int> int_it(std::cin),int_eof;
vector<int> ve(int_it,int_eof);
for(int i:ve){
cout<<i<<" ";
}
}
ostream_iterator
//ostream_iterator<T> out(os) 构造方法,out将类型为T的值写入输入流OS
//ostream_iterator<T> out(os,c) 构造方法,out将类型为T的值写入输入流OS,并在每个值后加一个c
istream_iterator<int> int_it(std::cin),int_eof;
vector<int> ve(int_it,int_eof);
ostream_iterator<int> out_iter(cout," ");
for (auto e:ve) {
//使用迭代器给cout赋值,并将迭代器向后移一位;
*out_iter++=e;
}
Get an iterator of the file input stream
#include <iostream>
#include <fstream>
#include <zconf.h>
#include <sstream>
#include <iterator>
#include "resource/PersonInfo.h"
using namespace std;
int main() {
vector<PersonInfo> ve;
PersonInfo personInfo;
ifstream in("D:/CLProj/IO/resource/a.text");
//得到流的迭代器和尾后迭代器,一旦IO遇到错误或读到文件结尾,迭代器的值就会和尾后迭代器相等;
istream_iterator<string> in_iter(in), in_end;
while (in_iter!=in_end){
cout<<*in_iter++<<endl;
}
}
Get an iterator of the file output stream
#include <iostream>
#include <fstream>
#include <zconf.h>
#include <sstream>
#include <iterator>
#include "resource/PersonInfo.h"
using namespace std;
int main() {
vector<PersonInfo> ve;
PersonInfo personInfo;
personInfo.setName("何宇");
personInfo.setPhones({"1231221234","12131357624"});
ve.push_back(personInfo);
ofstream out("D:/CLProj/IO/resource/a.text",ofstream::app);
ostream_iterator<string> in_iter(out," ");
for(PersonInfo pI:ve){
*in_iter++=pI.name;
for(auto phone:pI.phones)
*in_iter++=phone;
*in_iter++="\n";
}
}
何必 13788889999 13277778888
吴洋 18955557777 13877772222
鲁中 17833332222 17833332222
郭德纲 13922228888
李云 17233339999 18712348976
汪悦 17233332299 18712444476
何世清 18023458921 13476324587
何宇 1231221234 12131357624
Reverse iterator
#include <iostream>
#include <fstream>
#include <zconf.h>
#include <sstream>
#include <iterator>
#include "resource/PersonInfo.h"
using namespace std;
int main() {
// 反向迭代器的结尾指向迭代器开头之前的一个位置
string s("Hello World!");
auto rbeg=s.crbegin();
auto rend=s.crend();
while (rbeg!=rend){
cout<<*rbeg<<" ";
++rbeg;
}
}
to sum up:
unique(beg,end) //排重算法
uniuqe(beg,end,comp)//使用comp来比较两个元素是否相等,即调用==来判断是否相等
find(beg,end,val)//在迭代器范围内寻找变量val第一次出现的位置
find_if(beg,end,pred)//查找第一个令pred判断为真的元素
reverse(beg,end)//反转迭代器内的元素
reverse(beg,end,dest)//将反转后的元素拷贝至dest,不改变原来的值;
remove_if(beg,end,lambda)//lambda表达式为真,则将迭代器范围内的值移除
remove_if(v1.beg,v1.end,back_inserter(v2),pred)//将移除的元素拷贝到v2中
replace(beg,end,oldValue,newValue)//在迭代器范围内使用新值代替旧值
replace_if(beg,end,pred,newValue)//,如果元素使pred为真在迭代器范围内使用新值代替旧值。
replace_copy_if(beg,end,dest,pred,newValue)//如果元素使pred为真在迭代器范围内使用新值代替旧值,并将旧值拷贝至dest中
list和forward_list容器中的算法:
list.merge(list2) 将list2中的元素并入list,并且将List2中的元素删除,两者必须是有序的,合并后使用<排序
list.merge(list2,comp) 将list2中的元素并入list,并且将List2中的元素删除,使用comp中的规则排序
list.remove(val) 删除元素val;
list.remove(val,pred),删除使函数为真的元素
list.reverse(),是list的元素反转;
list.sort() 按照默认顺序以"<"排序
list.sort(comp) 以comp比较大小排序
list.unique() 删除重复元素
list.unique(comp) 使用给定的二元谓词判断是否相等