cpp的STL算法

cpp的STL算法

什么是stl算法

操作stl集合的一堆方法。很方便,他们就是一堆工具。

你只要熟悉stl就可以很方便的使用他们啦。

先明白算法有哪些,有什么作用,然后熟悉一部分常用的,其他的在实践中时候用

stl算法的分类

非变序算法

计数算法
    count,count_if
搜索算法
    search,seach_n
    find,find_if,find_end,find_first_of,adjacent_find
比较算法
    equal,mismatch,lexicographical_compare

变序算法

初始化算法
    fill,fill_n,generate,generate_n
修改算法
    for_each,transform
复制算法
    copy,copy_backward
删除算法
    remove,reomve_if,remove_copy,remove_copy_if
    unique,unique_copy
替换算法
    replace,replace_if
排序算法
    sort,stab_sort,partial_sort

分区算法
    partion,stable_partition
可用于排序容器的算法
binary_search,lower_bound,upper_bound

stl算法的应用

计算元素的个数
查找元素
在集合中搜索元素或序列
将容器中的元素初始化为指定的值
使用for_each处理范围内的元素
使用transtrom 对范围进行编号
复制和删除操作
替换值以及满足给定条件的元素
排序,在有序集合中搜索以及删除重复元素
将范围分区

在有序集合中插入元素
//
//  main.cpp
//  use_stl_algorithm
//
//  Created by bikang on 16/11/1.
//  Copyright (c) 2016年 bikang. All rights reserved.
//

#include <iostream>
#include <algorithm>
#include <vector>
#include <list>

using namespace std;

template <typename T>
class PrintClass {
public:
    void operator()(const T& elem)const{
        cout << elem << " ";
    }
};


template <typename T>
bool isEven(const T& number) {
    return ((number%2) == 0);
}

template <typename T>
T addData(const T & v1,const T & v2) {
    return (v1+v2);
}


//在容器中计算元素个数和查找元素
void tstlalg1();
//查找序列
void tsearch();
//容器初始化fill 偏移范围 fill_n 开始位置,个数,数值
//generate随机初始化
void tfill();
//transform 容器的内容的变换
void ttransform();
//测试复制和删除
//copy,copy_backward,remove,remove_if
//replace
//partition  stable_partition
void tdelCopy();

//sort binary_search unique 排序 查找 去重复
void  tsort();



int main(int argc, const char * argv[]) {
    //tstlalg1();
    //tsearch();
    //tfill();
    //ttransform();
    //tdelCopy();
    tsort();
    return 0;
}

void  tsort(){
    vector<string> vec1;
    vec1.push_back("tom");
    vec1.push_back("tim");
    vec1.push_back("tim");
    vec1.push_back("tam");
    vec1.push_back("tam");
    vec1.push_back("kim");
    vec1.push_back("kim");
    for_each(vec1.begin(), vec1.end(), PrintClass<string>());cout << endl;

    //排序
    sort(vec1.begin(), vec1.end());
    for_each(vec1.begin(), vec1.end(), PrintClass<string>());cout << endl;

    //查找
    bool searchRes = binary_search(vec1.begin(), vec1.end(), "tom");
    if(searchRes){
        cout << "find ok"<<endl;
    }else{
        cout << "find faild"<<endl;
    }
    searchRes = binary_search(vec1.begin(), vec1.end(), "to1m");
    if(searchRes){
        cout << "find ok"<<endl;
    }else{
        cout << "find faild"<<endl;
    }

    //去重复
    vector<string>::iterator ite;
    ite = unique(vec1.begin(), vec1.end());
    for_each(vec1.begin(), vec1.end(), PrintClass<string>());cout << endl;
    vec1.erase(ite, vec1.end());
    for_each(vec1.begin(), vec1.end(), PrintClass<string>());cout << endl;


    //有序插入,优选的最前和最靠后的位置
    string lowerStr = "ad";
    ite = lower_bound(vec1.begin(), vec1.end(),lowerStr);
    vec1.insert(ite, lowerStr);
    for_each(vec1.begin(), vec1.end(), PrintClass<string>());cout << endl;

    string upperStr = "ss";
    ite = upper_bound(vec1.begin(), vec1.end(),upperStr);
    vec1.insert(ite, upperStr);
    for_each(vec1.begin(), vec1.end(), PrintClass<string>());cout << endl;


}

void tdelCopy(){

    list<int> l1;
    for(int j =0;j<10;++j){
        l1.push_back(j);
    }
    for_each(l1.begin(), l1.end(), PrintClass<int>());cout << endl;

    //copy
    vector<int> vec1(l1.size() *2);
    vector<int>::iterator ite;
    ite = copy(l1.begin(), l1.end(),vec1.begin());
    for_each(vec1.begin(), vec1.end(), PrintClass<int>());cout << endl;
    copy_backward(l1.begin(), l1.end(), vec1.end());
    for_each(vec1.begin(), vec1.end(), PrintClass<int>());cout << endl;

    //remove
    remove(vec1.begin(), vec1.end(), 0);
    for_each(vec1.begin(), vec1.end(), PrintClass<int>());cout << endl;
    //remove if

    remove_if(vec1.begin(), vec1.end(), [](int i){return i%2==0;});
    for_each(vec1.begin(), vec1.end(), PrintClass<int>());cout << endl;

    //replace
    replace(vec1.begin(), vec1.end(), 1, 21);
    for_each(vec1.begin(), vec1.end(), PrintClass<int>());cout << endl;
    //replace if
    replace_if(vec1.begin(), vec1.end(), [](int i){return i%2==1;}, 55);
    for_each(vec1.begin(), vec1.end(), PrintClass<int>());cout << endl;

    //partition
    partition(l1.begin(), l1.end(),[](int i){return i%2==1;});
    for_each(l1.begin(), l1.end(), PrintClass<int>());cout << endl;
    //stable_partition
    stable_partition(l1.begin(), l1.end(),[](int i){return i%2==1;});
    for_each(l1.begin(), l1.end(), PrintClass<int>());cout << endl;


}

void ttransform(){

    string str1 = "this is a simple language!";
    string str1low;
    str1low.resize(str1.size());
    transform(str1.begin(), str1.end(), str1low.begin(), (int(*)(int))toupper);
    cout << str1low << endl;

    //测试加法
    vector<int> vec1;
    for (int i =0; i<10; ++i) {
        vec1.push_back(i);
    }

    vector<int> vec2;
    for (int i =20; i<30; ++i) {
        vec2.push_back(i);
    }

    vector<int> res;
    res.resize(10);

    //两个容器的内容相加
    transform(vec1.begin(), vec1.end(), vec2.begin(), res.begin(), addData<int>);
    for_each(vec1.begin(), vec1.end(), PrintClass<int>());cout << endl;
    for_each(vec2.begin(), vec2.end(), PrintClass<int>());cout << endl;
    for_each(res.begin(), res.end(), PrintClass<int>());cout << endl;

}

void tfill(){
    cout << "tfill" << endl;
    vector<int> vec1(3);
    fill(vec1.begin(), vec1.end(), 9);
    for_each(vec1.begin(), vec1.end(), PrintClass<int>());cout << endl;

    vec1.resize(6);
    fill_n(vec1.begin()+3, 3, 3);
    for_each(vec1.begin(), vec1.end(), PrintClass<int>());cout << endl;
    vec1.resize(10);
    generate(vec1.begin()+6, vec1.end(), rand);
    for_each(vec1.begin(), vec1.end(), PrintClass<int>());cout << endl;
    vec1.resize(12);
    generate_n(vec1.begin()+10, 2, rand);
    for_each(vec1.begin(), vec1.end(), PrintClass<int>());cout << endl;

}

void tsearch(){
    cout << "tsearch" << endl;
    vector<int> vec1;
    for (int i =0; i<10; ++i) {
        vec1.push_back(i);
    }
    for_each(vec1.begin(), vec1.end(), PrintClass<int>());cout << endl;

    list<int> l1;
    for(int j =3;j<5;++j){
        l1.push_back(j);
    }

    //search查找
    vector<int>::iterator ite;
    ite = search(vec1.begin(), vec1.end(),l1.begin(), l1.end());
    if(ite != vec1.end()){
        cout << "pos=" << distance(vec1.begin(), ite);
    }else{
        cout << " search faild";
    }


}

void tstlalg1(){
    cout << "start" << endl;
    vector<int> vec1;
    for (int i =0; i<10; ++i) {
        vec1.push_back(i);
    }
    for_each(vec1.begin(), vec1.end(), PrintClass<int>());cout << endl;
    //查找 数据数量
    long numCount = 0;
    int find_data = 3;
    numCount = count(vec1.begin(), vec1.end(), (int)find_data);
    cout << "numCount=" <<numCount << endl;

    //查找 数据数量
    size_t npos = count_if(vec1.begin(), vec1.end(), isEven<int>);
    cout << "npos=" <<npos << endl;
    //闭包查找 数据数量
    npos =count_if(vec1.begin(), vec1.end(), [](int i){return i%4==0;});
    cout << "npos=" <<npos << endl;

    //find查找数据的位置
    vector<int>::iterator ite;
    ite = find(vec1.begin(), vec1.end(), find_data);
    if(ite != vec1.end()){
        cout << "find ok " << *ite << endl;
    }else{
        cout << "find faild" << endl;
    }

    //find_if查找数据的位置
    ite = find_if(vec1.begin(), vec1.end(), [](int i){return i%4==0;});
    if(ite != vec1.end()){
        cout << "find ok " << *ite << endl;
    }else{
        cout << "find faild" << endl;
    }


}







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
仅仅是作为搬运工。 算法精粹——举一反三,抛弃题海战术 本书的目标读者是准备去硅谷找工作的码农,也适用于在国内找工作的码农,以及刚接触ACM算法竞赛的新手。 市场上讲解算法的书已经汗牛充栋,为什么还要写这本书呢?主要原因是我对目前市场上的大部分算法书都不太满意。 本书有如下特色: 背后有强大的AlgoHub支持。 本书的所有题目,都可以在 www.algohub.org(即将上线) 上在线判断代码。这样的一大好处是,读者可以边看书,边实现自己的代码,然后提交到网站上验证自己的想法是否正确。AlgoHub的使命是成为最好的算法学习和交流平台。AlgoHub囊括了 POJ, ZOJ, leetcode, HackerRank 等网站的经典题目(一些质量不高的题目则忽略),且 AlgoHub有非常简单的加题系统,用户不需要写一行代码即可自己添加题目,所以AlgoHub的题库还在飞速增长中。 每道题都有完整的代码。 市场上的大部分书,都会讲思路,但给出的代码都是片段,不是完整可编译的代码。本书每题都有完整的代码,且每个代码经过千锤百炼,保证可读性的前提下尽可能简短,方面读者在面试中能快速写出来。 每道题都有多种解法。 本书的宗旨是,用尽可能少的题目,覆盖尽可能多的算法。本书中的的每道题都有多种解法,每种解法不是简单的小改进,而是完全不同的思路,力求举一反三,让读者触类旁通。 本书支持多种主流编程语言。 目前支持 Java, C++, C#, Python, Ruby, JavaScript, Swift, Scala, Clojure, 将来还会支持更多编程语言。 在线阅读 https://www.gitbook.com/book/soulmachine/algorithm-essentials/ 内容目录 介绍 线性表 数组 Remove Duplicates from Sorted Array Remove Duplicates from Sorted Array II Longest Consecutive Sequence Two Sum 3Sum 3Sum Closest 4Sum Remove Element Move Zeroes Next Permutation Permutation Sequence Valid Sudoku Trapping Rain Water Rotate Image Plus One Climbing Stairs Set Matrix Zeroes Gas Station Candy Majority Element Rotate Array Contains Duplicate Contains Duplicate II Contains Duplicate III Product of Array Except Self Game of Life Increasing Triplet Subsequence 单链表 Reverse Linked List Odd Even Linked List Add Two Numbers Reverse Linked List II Partition List Remove Duplicates from Sorted List Remove Duplicates from Sorted List II Rotate List Remove Nth Node From End of List Swap Nodes in Pairs Reverse Nodes in k-Group Copy List with Random Pointer Linked List Cycle Linked List Cycle II Reorder List LRU Cache Palindrome Linked List 字符串 Valid Palindrome Implement strStr() String to Integer (atoi) Add Binary Longest Palindromic Substring Regular Expression Matching Wildcard Matching Longest Common Prefix Valid Number Integer to Roman Roman to Integer Count and Say Anagrams Valid Anagram Simplify Path Length of Last Word Isomorphic Strings Word Pattern 栈和队列 栈 Min Stack Valid Parentheses L
C++ STL是C++标准模板库(Standard Template Library)的简称。它是C++的一个重要组成部分,提供了一系列的通用模板类和函数,用于处理常见的数据结构和算法问题。 学习C++ STL有以下几个方面的好处: 1. 提高开发效率:STL提供了大量现成的数据结构和算法,比如向量(vector)、链表(list)、队列(queue)、堆栈(stack)等,以及排序、查找、计数、遍历等算法。使用STL可以避免重复造轮子的过程,通过简单的调用就可以快速编写高效的代码,提高开发效率。 2. 提高代码质量:STL是由专业的C++程序员设计和实现的,其设计遵循了面向对象的思想,并使用了模板元编程等技术。使用STL可以提高代码的模块化程度,减少重复代码,使代码更加清晰、简洁和可维护。 3. 为学习其他编程语言打下基础:STL采用了一种通用、抽象的设计,其思想和理念对于学习其他编程语言也是有借鉴意义的。通过学习STL,可以更好地理解数据结构和算法的设计与实现,为学习其他编程语言打下坚实的基础。 要学习C++ STL,可以从以下几个方面入手: 1. 理解STL的组成部分:了解STL的组成部分,包括容器(container)、迭代器(iterator)、算法(algorithm)、函数对象(function object)、适配器(adapter)等。理解它们之间的关系和作用,掌握各个组成部分的用法和特点。 2. 学习STL的常用容器和算法:熟悉STL提供的常用容器和算法,如向量(vector)、链表(list)、队列(queue)、堆栈(stack)等,以及排序、查找、计数、遍历等算法。了解其基本的操作和用法,掌握它们的时间复杂度和使用场景。 3. 理解STL内部实现原理:了解STL内部的实现原理,包括对容器和算法的底层实现,例如迭代器的实现、算法的实现方式和优化等。理解这些原理有助于更好地理解和使用STL,以及优化代码性能。 总之,学习C++ STL对于提高C++编程能力和开发效率非常重要。通过学习STL,可以更好地掌握C++的数据结构和算法,提高代码质量和可维护性,为进一步学习和应用其他编程语言打下坚实的基础。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值