Home Item 4 (1/2) - array of std(中文)
Post
Cancel

Item 4 (1/2) - array of std(中文)

c++ 新的容器類型: array

覺得 c++ 的 array 太難用 ? 像是 int[5] , 沒提供什麼成員函數來協助 coder, 沒關係,可以使用 std::array.

當需要一個固定大小的陣列,並且知道其大小時,可以使用 c++11 std::array。它比內置的陣列更加安全和方便,因為它提供了陣列的大小信息和一些方便的成員函數。

直接看 code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <array>

int main()
{
    // 創建一個包含5個整數的固定大小的陣列
    std::array<int, 5> arr = { 1, 2, 3, 4, 5 };

    // 使用範圍for循環遍歷陣列並打印每個元素
    for (int x : arr) {
        std::cout << x << " ";
    }
    std::cout << std::endl;

    // size()
    std::cout << "array size:" << arr.size() << std::endl;

    // at()
    std::cout << "element at index 4:" << arr.at(4) << std::endl;

    // 使用正向迭代器遍歷陣列並打印每個元素
    std::cout << "Forward traversal:" << std::endl;
    for (auto it = arr.begin(); it != arr.end(); ++it) {
        std::cout << *it << " ";
    }
    std::cout << std::endl;

    // 使用反向迭代器遍歷陣列並打印每個元素
    std::cout << "Reverse traversal:" << std::endl;
    for (auto it = arr.rbegin(); it != arr.rend(); ++it) {
        std::cout << *it << " ";
    }
    std::cout << std::endl;

    // fill()
    arr.fill(0);

    // 打印 fill 之後的結果
    std::cout << "after fill(0)" << std::endl;
    for (auto it = arr.begin(); it != arr.end(); ++it) {
        std::cout << *it << " ";
    }
    std::cout << std::endl;

    return 0;
}

onlinegdb

執行結果

Desktop View

使用時機:

std::array 提供了一些內建陣列所不具備的特性,這些特性包括:

  1. 大小信息: std::array 包含了陣列的大小信息,這使得在編譯時就可以知道陣列的大小。這樣可以避免使用sizeof等運算符來查詢陣列的大小。
  2. 安全的索引訪問: std::array 提供了at() 函數,可以進行安全的索引訪問,它會檢查索引的有效性,並在索引越界時拋出異常。
  3. 迭代器支持: std::array 支持正向和反向迭代器,可以使用begin()和end()函數來獲取首尾迭代器。
  4. 元素存取: 提供了像 front()、back()、operator[] 等成員函數,可以方便地訪問陣列的首尾元素,以及通過索引訪問陣列的特定元素。
  5. 賦值和填充: 提供了 fill() 函數,可以將陣列中的所有元素設置為特定值,以及支持拷貝賦值和移動賦值。

上述的 code 都有示範到,下次你可以試試看用 std::array,會覺得世界美好很多。哈!

☝ツ☝

This post is licensed under CC BY 4.0 by the author.

👈 ツ 👍