STL 常用算法(一) - 遍历 & 查找算法

概述

  • 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;
发布了515 篇原创文章 · 获赞 135 · 访问量 30万+

猜你喜欢

转载自blog.csdn.net/liyazhen2011/article/details/103201255