zoukankan      html  css  js  c++  java
  • 容器的常用“操作”或“算法”

    使用泛型算法必须包含 algorithm 头文件:

    #include <algorithm> 

    使用泛化的算术算法必须包含numeric 头文件:

    #include <numeric>
    操作
    用法或功能 操作名称 备注
       .begin()  
       .end()  
       .size()  
       push_back  
       erase  
       find  

    另外,泛型算法的相关章节提到一个“迭代器适配器”,在容器的算法和操作中有一定用处:“ back_inserter”

    算法
    用法或功能 算法名称 备注
      accumulate  
      find_first_of  
      fill  
      fill_n  
       copy  当“要以一个已存在的容器为副本创建新容器时,更好的方法是直接用输入范围作为新构造容器的初始化式”,而不是copy
       replace   
      replace_copy   
      unique_copy _copy版本,unique_copy(vec.begin(), vec.end(), output); 该算法将输入范围中不重复的值复制到目标迭代器。
       unique  
       stable_sort  
       count_if  
      sort  标准库定义的四种排序算法最简单的一个:使字符串中的单词按照“字典次序排列”
      stable_sort 稳定排序:保留相等元素的原始相对位置
         
         
         

     在学习“泛型算法”这一节的相关算法时,首次遇到“谓词”这个概念:“谓词是做某些检测的函数,返回用于条件判断的类型,指出条件是否成立。”,《C++ Primer》中指出:“使用这些算法,还需要一个配套的实用函数,,称为谓词”,下面是两个谓词使用的例子,注意它与普通函数使用的不同:

    1      // comparison function to be used to sort by word length 
    2      bool isShorter(const string &s1, const string &s2) 
    3      { 
    4          return s1.size() < s2.size(); 
    5      } 
    1     // determine whether a length of a given word is 6 or more 
    2      bool GT6(const string &s) 
    3      { 
    4           return s.size() >= 6; 
    5      }

    这两个谓词函数都是有形参的,但在使用他们的时候,仅仅用到了名字,如下:

    1  // sort words by size, but maintain alphabetic order for words of the same size 
    2      stable_sort(words.begin(), words.end(), isShorter);
    1      vector<string>::size_type wc = 
    2                   count_if(words.begin(), words.end(), GT6); 

    这点的具体实现还要去算法“stable_sort和count_if”中去查看。

     备注“算法的搜索方法”:

    在MSDN中搜索“stable_sort”,打开“stable_sort - MSDN – the Microsoft Developer Network‎”以后,左侧的树形菜单列出“algorithm”头文件下的相关算法,很多,有必要去了解一下。

  • 相关阅读:
    IntelliJ IDEA 2017 反向代理工具新方法激活
    如何去掉idea里mybatis的.xml文件 sql 语句背景色
    eclipse、idea切换大小写的快捷键
    pageHelper没有分页效果的问题
    springboot使用thymeleaf 解析异常
    SpringBoot发送简单文本邮件
    IDEA中使用git详细步骤
    解决 git branch -a 无法全部显示远程的分支,只显示master分支
    git常用命令
    异常处理
  • 原文地址:https://www.cnblogs.com/tingshuixuan2012/p/3050521.html
Copyright © 2011-2022 走看看