• 数组的选择固定大小数组模板array存在的意义!


        主要就是为了使用的方便,更加容易和algorithm的算法结合的更好!

    #include <iostream> 
    #include <ctime> 
    #include <array> 
    
    #include <functional> 
    #include <algorithm> 
    
    #include <boost\array.hpp> 
    
    using namespace std; 
    using namespace std::tr1; 
    
    int getRand() 
    { 
       return rand()% 90 + 10; // 保证是两位数! 
    } 
    
    template < typename Iter > // 只支持int,这里只是用来演示 
    void print( Iter first,Iter last ) 
    { 
       copy( first,last, ostream_iterator< int >( cout," ") ); 
       cout<< endl; 
    } 
    
    int main() 
    { 
       srand( (unsigned)time( NULL ) ); 
    
       int test1_array[20]; 
       generate( test1_array,test1_array + 20, getRand ); 
       print( test1_array,test1_array + 20 ); 
       sort( test1_array,test1_array+20, greater<int>() ); 
       print( test1_array,test1_array + 20 ); 
       // 无法用print倒着输出! 
    
       cout<<"大小是"<< sizeof(test1_array) / sizeof(int) <<endl; 
    
       array< int , 20 > test2_array; 
       generate( test2_array.begin(), test2_array.end(), getRand ); 
       print( test2_array.begin(), test2_array.end() ); 
       sort( test2_array.begin(), test2_array.end() ); 
       print( test2_array.begin(),test2_array.end() ); 
       cout<< "大小是"<<test2_array.size()<<endl; 
    
       // 优势,倒着输出,如此简单! 
       print( test2_array.rbegin(), test2_array.rend() ); 
    
       boost::array< int, 24 > test3_array; 
       generate( test3_array.begin(), test3_array.end(), getRand ); 
       print( test3_array.begin(),test3_array.end() ); 
       print( test3_array.rbegin(),test3_array.rend() ); 
    
       return 0; 
    } 

    // 另外boost::array和tr1::array使用一样!
    通过代码相信大家都已经看到了,使用这种固定数组模板能够用起来更方便,而且在效率上也不会有太大的开销。
    个人对此的一些建议:
    1.当我们只是把一个数组用来存放一些东西而且是固定大小的时候我们都使用C风格的数组。
    2.如果我们对它的操作频繁涉及到很多算法的时候,我们可以考虑array模板!
    3.当大小需要变动的时候建议使用其它标准容器!

  • 相关阅读:
    weka 文本分类(1)
    python 笔记1
    PAT乙级 1028. 人口普查(20)
    PAT乙级 1027. 打印沙漏(20)
    PAT乙级 1026. 程序运行时间(15)
    Eclipse常用快捷键
    MyBatis源码分析(各组件关系+底层原理
    springmvc异常处理
    Elasticsearch学习(一)————简单命令
    mybatis传入参数类型parameterType详解
  • 原文地址:https://www.cnblogs.com/rollenholt/p/2429823.html
Copyright © 2020-2023  润新知