概述
- STL常用算法主要分布在<algorithm>,<functional>和<numeric>中
- <algorithm>定義了比較、交換、查找、周遊、複制、修改等操作。
- <numeric>定義了簡單數學運算的模闆函數。
- <functional>定義了模闆類,用以聲明函數對象。
常用算法
1. for_each
常用的周遊算法。
vector<int> v = {1, 5, 3, 8};
for_each(v.begin(), v.end(), [](int val) {
cout << val << endl;
});
2. transform
将容器中的元素搬移到另一個容器中。
vector<int> s = { 1,4,7 };
vector<int> d;
d.resize(s.size()); //提前開辟空間,否則無法正常搬移
transform(s.begin(), s.end(), d.begin(), [](int val){
return val;
});
3. find
查找指定元素。找到時,傳回該元素的疊代器;找不到時,傳回end()。
vector<int> v = { 1,4,7 };
auto res = find(v.begin(), v.end(), 4);
if (res == v.end()){
cout << "沒有找到元素" << endl;
}
else{
cout << "找到元素"<< *res << endl;
}
4. find_if
按照條件查找元素。找到時,傳回該元素的疊代器;找不到時,傳回end()。
vector<int> v = { 1,4,7 };
auto res = find_if(v.begin(), v.end(), [](int val) {
return val > 6;
});
if (res == v.end()){
cout << "沒有找到元素" << endl;
}
else{
cout << "找到元素 "<< *res << endl;
}
5. adjacent_find
查找相鄰重複的元素。找到時,傳回指向相鄰元素中第一個元素的疊代器;找不到時,傳回end()。
vector<int> v = { 1,4,7,7 };
auto res = adjacent_find(v.begin(), v.end());
cout << *res << endl;
6. binary_search
查找指定的元素。找到時傳回true,否則傳回false。(注:無序序列中不可用)
vector<int> v = { 1,4,7,7 };
bool res = binary_search(v.begin(), v.end(), 7);
cout << res << endl;
7. count
統計元素出現的次數。
vector<int> v = { 1,4,7,7 };
int res = count(v.begin(), v.end(), 7);
cout << "等于7的元素個數: " << res << endl;
8.count_if
按照條件統計元素出現的次數。
vector<int> v = { 1,4,7,7 };
int res = count_if(v.begin(), v.end(), [](int val) {
return val > 5;
});
cout << "大于5的元素個數為: " << res << endl;