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;

 

 

 

 

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值