• 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...
     
  • 相关阅读:
    ASP.NET WebAPI2 发布之后404 Not Found
    WPF MVVM TreeView 实现 右键选中 右键菜单
    Asp.Net MVC4+EF6 Code First 权限管理系统 源码下载
    C# Winform DataGrid 绑定List<> Or ObservableCollection<> 类型无法自动刷新问题
    VMWare 安装时报错 tools-windows.msi failed报错解决办法
    HashMap 扩容机制
    POI解析Excel封装工具
    poi API
    简单echars说明和使用
    比较运算符compareTo()、equals()、==之间的区别
  • 原文地址:https://www.cnblogs.com/zhuyp1015/p/2620767.html
Copyright © 2020-2023  润新知