# STL惯用法[持续更新中...]

## 数组与指针

### 查找

``````#include <iostream>
#include <algorithm>

using namespace std;

int main(){
int arr[] = {2,3,5,6,1};
if(end(arr) != find(begin(arr),end(arr),3)){
cout << "finded" << endl;
}else{
cout << "not finded" << endl;
}
}
``````

``````#include <iostream>
#include <algorithm>

using namespace std;

int main(){
if(any_of(begin(arr),end(arr),[](int i){return i==3;})){
cout << "finded" << endl;
}else{
cout << "not finded" << endl;
}
}
``````

### 比较

1. 比较两个数组/容器是否相等
``````int arr1[]={1,2,3,4,5};
int arr2[]={1,2,3,6,5};
cout << equal(arr1,arr1+5,arr2) << endl;
``````
1. 比较两个数组/容器哪里不相等
``````int arr1[]={1,2,3,4,5};
int arr2[]={1,2,3,6,5};
pair<int*,int*> p = mismatch(arr1,arr1+5,arr2);
cout <<"pos:"<< distance(arr1,p.first) << "=>" << *(p.first) << " "<< *(p.second) << endl;
``````

### 过滤

``````vector<type_t> inVals;
vector<type_t> outVals;
vector<type_t> oValidTypes;
copy_if(inVals.begin(),inVals.end(),back_inserter(outVals),[&](type_t oVals)->bool{
return (find(oValidTypes.begin(),oValidTypes.end(),oVals) != oValidTypes.end());
});
``````

### 移除

1. 移除重复
``````vector<type_t> oVals;
oVals.erase(unique(oVals.begin(),oVals.end()),oVals.end());
``````
1. 移除无效
``````vector<type_t> oVals;
oVals.erase(remove_if(oVals.begin(),oVals.end(),[](type_t oVal)->bool{
return !IsValid(oVal);
}),oVals.end());
``````

### 分离

``````vector<pair<first_t,secend_t>> oVals;
vector<first_t> ofirst;
vector<secend_t> oSecend;
transform(oVals.begin(),oVals.end(),back_inserter(ofirst),[](pair<first_t,secend_t> const& oVal){
return oVal.first;
});
transform(oVals.begin(),oVals.end(),back_inserter(oSecend),[](pair<first_t,secend_t> const& oVal){
return oVal.second;
});
``````

### 合并

``````vector<type_t> oVals;
map<type_t,int> oMap;
int i=0;
transform(oVals.begin(),oVals.end(),inserter(oMap,oMap.end()),
[&index](type_t oVal)->std::pair<type_t,int>{
return std::make_pair(oVal,i++);
}
);
``````

• `transform()`相当于函数式编程中的映射操作`map()`
• `copy_if`相当于函数式编程中的过滤操作`filter()`
• `accumulate()`相当于函数式编程中的归并操作`reduce()`

``````for(auto oVal:oVals){
ofirst.append(oVal.first);
oSecend.append(oVal.second);
}
``````