stl algorithm example

本文通过具体的代码示例介绍了 C++ 中标准模板库 (STL) 的几个常用函数,包括 find、find_if、transform 和 sort_heap 等,展示了如何使用这些函数来简化编程任务。
#include <vector>
#include <algorithm>
#include <iostream>

bool divby5(int x)
{
    return x % 5 ? 0 : 1;
}

int square(const int x)
{
    return x*x;
}

void find_sample()
{
    int num_find = 6;
    std::vector<int> v1;
    for (int i=0; i<10; i++) {
        v1.push_back(2*i);
    }
    std::vector<int>::iterator result;
    result = find(v1.begin(), v1.end(), num_find);

    if (result == v1.end()) {
        std::cout << "not found: " << num_find << std::endl;
    } else {
        std::cout << "found: " << result-v1.begin() << std::endl;
    }
}

void find_if_sample()
{
    std::vector<int> v(20);
    for (int i=0; i<v.size(); i++) {
        v[i] = (i+1) * (i+3);
        std::cout << v[i] << std::endl;
    }

    int count_find = 15; 
    std::vector<int>::iterator ilocation;
    ilocation = find_if(v.begin(), v.end(), divby5);
    const int num_find = count(v.begin(), v.end(), count_find);
    if (ilocation != v.end()) {
        std::cout << "find num less than 5: " << *ilocation << " at: " << ilocation-v.begin() << std::endl;
        std::cout << "find count equal 15: " << num_find << std::endl;
        std::cout << "less than 5 num is: " << count_if(v.begin(), v.end(), divby5) << std::endl;
    }
}

void transform_sample()
{
    std::vector<int> v1(20), v2(20);
    for (int i=0; i<v1.size(); i++) {
        v1[i] = (i+1) * (i+3);
    }

    generate_n(v1.begin(), 15, rand);
    
    transform(v1.begin(), v1.end(), v2.begin(), square);
    unique(v1.begin(), v1.end());
    sort(v1.begin(), v1.end());

    std::vector<int>::iterator ti;
    for (ti=v2.begin(); ti!=v2.end(); ti++) {
        std::cout << *ti << std::endl;
    }
}

void sort_heap_sample()
{
    std::vector<int> v1(20), v2(20);
    for (int i=v1.size(); i>0; i--) {
        v1[i] = (i+1) * (i+3);
    }

    make_heap(v1.begin(), v1.end());
    sort_heap(v1.begin(), v1.end());

    for (int i=0; i<v1.size(); i++) {
        std::cout << v1[i] << std::endl;    
    }
}

int main(int argc, char** argv)
{
    find_sample();
        find_if_sample();
    transform_sample();
    sort_heap_sample();
        
    return 0;
}

转载于:https://www.cnblogs.com/octave/p/4428772.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值