0
点赞
收藏
分享

微信扫一扫

C++标准模板库STL数组array

十里一走马 2022-02-23 阅读 56

class template

std::array

🔙返回目录(建议收藏):全面理解C++ STL标准模板库


[array目录]

1. 什么是array

template <class T, size_t N> class array;

array固定大小的序列容器,它们包含按严格线性序列排序的特定数量的元素。

2. array的定义

std::array<int,3> myarray = {5, 19, 77};

3. array成员函数

3.1 迭代器

迭代器功能
beginReturn iterator to beginning
endReturn iterator to end
rbeginReturn reverse iterator to reverse beginning
rendReturn reverse iterator to reverse end
cbeginReturn const_iterator to beginning
cendReturn const_iterator to end
crbeginReturn const_reverse_iterator to reverse beginning
crendReturn const_reverse_iterator to reverse end

举个例子

// array::begin example
#include <iostream>
#include <array>

int main ()
{
  std::array<int,5> myarray = { 2, 16, 77, 34, 50 };

  std::cout << "myarray contains:";
  for ( auto it = myarray.begin(); it != myarray.end(); ++it )
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

Output:
myarray contains: 2 16 77 34 50

3.2 array容量

容量功能
sizeReturn size
max_sizeReturn maximum size
emptyTest whether array is empty

举个例子

// array::size
#include <iostream>
#include <array>

int main ()
{
  std::array<int,5> myints;
  std::cout << "size of myints: " << myints.size() << std::endl;
  std::cout << "sizeof(myints): " << sizeof(myints) << std::endl;

  return 0;
}

Possible output:
size of myints: 5
sizeof(myints): 20

3.3 元素访问

访问函数功能
[]Access element
atAccess element
frontAccess first element
backAccess last element
dataGet pointer to data

举个例子

// array::front
#include <iostream>
#include <array>

int main ()
{
  std::array<int,3> myarray = {2, 16, 77};

  std::cout << "front is: " << myarray.front() << std::endl;   // 2
  std::cout << "back is: " << myarray.back() << std::endl;     // 77

  myarray.front() = 100;

  std::cout << "myarray now contains:";
  for ( int& x : myarray ) std::cout << ' ' << x;

  std::cout << '\n';

  return 0;
}

3.4 修饰函数

成员函数功能
fillFill array with value
swapSwap content
// swap arrays
#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 << '\n';

  std::cout << "second:";
  for (int& x : second) std::cout << ' ' << x;
  std::cout << '\n';

  return 0;
}

Output:
first: 11 22 33 44 55
second: 10 20 30 40 50
举报

相关推荐

0 条评论