c++中的algorithm库

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/luoyexuge/article/details/81813860

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";






}

猜你喜欢

转载自blog.csdn.net/luoyexuge/article/details/81813860