zoukankan      html  css  js  c++  java
  • C++ 11 array

    Array 是一种大小固定的顺序容器。array 的申明:

    template <class T, size_t N>
    class array;
    Array内部只存储所包含的数据,哪怕是大小也只不过是个模板参数。和普通使用‘[]’语法申明的数组相比,只不过显得更加高效(操作高效),因为这个类添加了一系列的全局成员函数用来操作这些元素。下面来列一些主要的操作:
    // ‘[]’ 操作
    #include <iostream>
    #include <array>
     
    int main ()
    {
      std::array<int,10> myarray;
      unsigned int i;
     
      // assign some values:
      for (i=0; i<10; i++) myarray[i] = i * 10;
     
      // print content
      std::cout << "myarray contains:";
      for(int &i : myarray)
        std::cout << " " << i;
     
      std::cout << std::endl;
     
      return 0;
    }
    运行结果:
    C:\Windows\system32\cmd.exe /c  array.exe
    myarray contains: 0 10 20 30 40 50 60 70 80 90
    Hit any key to close this window...
     
     
    // data 成员函数:返回指向array第一个元素的指针
    #include <iostream>
    #include <cstring>
    #include <array>
     
    int main ()
    {
      const char* cstr = "Test string";
      std::array<char,12> charray;
     
      memcpy (charray.data(),cstr,12);
     
      std::cout << charray.data() << std::endl;
     
      return 0;
    }
    运行结果:
    C:\Windows\system32\cmd.exe /c  array.exe
    Test string
    Hit any key to close this window...
     
     
    // fill 函数,设置array内部的所有元素为指定值
    #include <iostream>
    #include <array>
     
    int main () {
      std::array<int,6> myarray;
     
      myarray.fill(5);
     
      std::cout << "myarray contains:";
      for ( int& x : myarray) { std::cout << " " << x; }
     
      std::cout << std::endl;
     
      return 0;
    }
    运行结果:
    C:\Windows\system32\cmd.exe /c  array.exe
    myarray contains: 5 5 5 5 5 5
    Hit any key to close this window...
     
     
     
    // swap 函数:交换两个array的内容,注意两个array必须是相同类型,相同大小
    #include <iostream>
    #include <array>
     
    int main ()
    {
      std::array<int,5> first = {10, 20, 30, 40, 50};
      std::array<int,5> second = {11, 22, 33, 44, 55};
     
      first.swap (second);
     
      std::cout << "first:";
      for (int& x : first) std::cout << " " << x;
      std::cout << std::endl;
     
      std::cout << "second:";
      for (int& x : second) std::cout << " " << x;
      std::cout << std::endl;
     
      return 0;
    }
    运行结果:
    C:\Windows\system32\cmd.exe /c  array.exe
    first: 11 22 33 44 55
    second: 10 20 30 40 50
    Hit any key to close this window...
     
  • 相关阅读:
    BZOJ4569 : [Scoi2016]萌萌哒
    2016浙江省赛过山车记
    BZOJ4546(原) : 三元组
    BZOJ4539 : [Hnoi2016]树
    BZOJ4537 : [Hnoi2016]最小公倍数
    BZOJ4538 : [Hnoi2016]网络
    BZOJ4527 : K-D-Sequence
    BZOJ4504 : K个串
    BZOJ4471 : 随机数生成器Ⅱ
    BZOJ3659 : Which Dreamed It
  • 原文地址:https://www.cnblogs.com/zhuyp1015/p/2620767.html
Copyright © 2011-2022 走看看