zoukankan      html  css  js  c++  java
  • c/c++ 通用的(泛型)算法 generic algorithm 总览

    通用的(泛型)算法 generic algorithm 总览

    特性:

    1,标准库的顺序容器定义了很少的操作,比如添加,删除等。

    2,问题:其实还有很多操作,比如排序,查找特定的元素,替换或删除一个特定值等,但是标准库并未给每个容器都定义成员函数来实现这些操作。

    3,解决办法:因为算法是相同的逻辑,只是进行运算的元素的类型是不同的。所以定义了一组与类型无关的通用的(泛型)算法:generic algorithm。它们实现了实现了上述标准库未提供的操作。

    4,好处:不用为每个容器实现上述的操作。

    大多数算法都定义在头文件algorithm中,数值相关的算法定义在头文件numeric中。

    关键概念:算法永远不会执行容器的操作。

    通用算法本身不会执行容器的操作,它们只会运行于迭代器之上,执行迭代器的操作。算法永远不会改变底层容器的大小。算法可能改变容器中保存的元素的值,也可能在容器内移动元素,但永远不会直接添加或删除元素。

    以find算法为例,find函数可以接受任意类型的容器

    #include <iostream>
    #include <vector>
    #include <algorithm>
    #include <list>
    
    using namespace std;
    
    int main(){
    
      //find vector<int>                                                            
      /*                                                                            
      int val = 121;                                                                
      vector<int> ivec{1,2,3,12,34};                                                
      vector<int>::const_iterator result = find(ivec.cbegin(), ivec.cend(),         
                                                val);                               
      cout << *result << endl;                                                      
      */
    
      //find list<string>                                                           
      /*                                                                            
      string s("aaa");                                                              
      list<string> li{"ddd","aaa1","aaa","dds"};                                    
      list<string>::const_iterator result =                                         
        find(li.cbegin(), li.cend(), s);                                            
      cout << *result << endl;                                                      
      */
    
      //find 内置数组                                                               
      int val = 22;
      int ar[] = {1,22,33,4};
      int* result = find(begin(ar), end(ar), val);
      cout << *result << endl;
      auto res1 = find(ar, ar + 4, val);
      cout << *res1 << endl;
    }
    

    c/c++ 学习互助QQ群:877684253

    本人微信:xiaoshitou5854

  • 相关阅读:
    zookeeper使用场景
    zookeeper安装配置
    hadoop 远程调试
    deep learning笔记
    Sentiment Analysis(1)-Dependency Tree-based Sentiment Classification using CRFs with Hidden Variables
    PRML阅读笔记 introduction
    Python 学习笔记(2)
    python nltk 学习笔记(5) Learning to Classify Text
    python nltk 学习笔记(4) Writing Structured Programs
    python nltk 学习笔记(3) processing raw text
  • 原文地址:https://www.cnblogs.com/xiaoshiwang/p/9660260.html
Copyright © 2011-2022 走看看