c++中的algorithm库

c++中的algorithm库,包含了所有vector、list、set、map操作能想到的一些函数,如查找,替换、排序、计数等常用的功能全部在里面,在这里虽然不像Java那样完全面向对象,方法全部在类里面,但是熟读algorithm库还是非常有必要,官网的链接http://www.cplusplus.com/reference/algorithm/  可以非常直接学习,代码也非常清晰易懂,下面自己写了几个例子:

#include <iostream>

#include <algorithm>
#include <vector>
using namespace std;


//参考http://www.cplusplus.com/reference/algorithm/

bool IsOdd (int i) {
    return ((i%2)==1);
}

int main() {
    int myints[] = { 5, 20, 51, 30, 20, 10, 22,50 };

    int len= sizeof(myints)/ sizeof(myints[0]);

    vector<int> myvector(myints,myints+len);

    cout<<myvector.size()<<endl;

    vector<int>::iterator  iter;

    //find函数查看vector是否包含某元素
    iter=  find(myvector.begin(),myvector.end(),50);

    if (iter != myvector.end()) {
        std::cout << "Element found in myvector: " << *iter << '\n';
    }// 30
    else {
        std::cout << "Element not found in myvector\n";
    }


    //根据条件来查看vector是否包含某元素
    std::vector<int>::iterator it = std::find_if (myvector.begin(), myvector.end(), IsOdd);
    std::cout << "The first odd value is " << *it << '\n';


    std::vector<int>::iterator iter1 =
            std::find_if_not (myvector.begin(), myvector.end(), [](int i){return i%2;} );
    std::cout << "The first even value is " << *iter1 << '\n';

    //计数工具  一直接对数组计数
    int mycount = std::count (myints, myints+8, 10);
    std::cout << "10 appears " << mycount << " times.\n";

    // counting elements in container:
    //对vector计数
    mycount = std::count (myvector.begin(), myvector.end(), 20);
    std::cout << "20 appears " << mycount  << " times.\n";

    //按照条件计数
     mycount = count_if (myvector.begin(), myvector.end(), IsOdd);
    std::cout << "myvector contains " << mycount  << " odd values.\n";


    //search_n 找位置情况,其中1表示从第几个20开始找
    it = std::search_n (myvector.begin(), myvector.end(), 1, 20);

    if (it!=myvector.end())
        std::cout << "two 30s found at position " << (it-myvector.begin()) << '\n';
    else
        std::cout << "match not found\n";






}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值