STL容器_001_array

pre

先来看看C风格数组

#include<iostream>
using namespace std;
int main(int argc, char const *argv[]) {
    //array测试
    int arr[10];
    arr[0] = 1;
    int arr1[] = {1,2,3,4,5};

    int* p = arr1;
    cout <<"*p = "<< *p << endl;
    cout <<"*(p+1) = "<< *(p+1) << endl;

    //计算arr1的长度
    int len = sizeof(arr1)/sizeof(arr1[0]);
    for (size_t i = 0; i <len ; i++)
    {
        cout << arr1[i] << endl;
    }
    arr1[5] = 9;    //越界
    cout<<"越界后"<<endl;
    int len1 = sizeof(arr1)/sizeof(arr1[0]);
    for (size_t i = 0; i <len1 ; i++)
    {
        cout << arr1[i] << endl;
    }
    return 0;
}

是什么

数组包装成的容器

template<
    class T,
    std::size_t N
> struct array;

传两个参数,在定义时需要指定数组的 大小元素类型.

🍅 特点:

  • 不能增长
  • 直接把指针拿来当迭代器

为什么

C 风格的数组更加灵活和简洁,但缺乏安全性和可读性;为了享受到算法/仿函数的好处.

怎么样

#include<iostream>
#include<algorithm>
#include<array>		//头文件
using namespace std;

void print_array(auto arr){
    for_each(arr.begin(), arr.end(), [](int x){cout << x << " ";});
    cout << endl;
}

int main(int argc, char const *argv[]) {
    //array测试
    int arr[3] = {10, 20, 30};
    arr[0] = 1;
    int arr1[] = {1,2,3,4,5};
    array<int, 3> arr2{1, 2, 3};
    
    //访问
    cout<<"arr2[0] = "<<arr2[0]<<endl;
    cout<<"arr2.at(0) = "<<arr2.at(0)<<endl;
    cout<<"arr2.front() = "<<arr2.front()<<endl;
    cout<<"arr2.back() = "<<arr2.back()<<endl;

    //容量
    cout<<"arr2.size()"<<arr2.size()<<endl;
    cout<<"arr2.empty()"<<arr2.empty()<<endl;

    //成员函数的swap  交换 arr2 和 arr3 它们的大小必须相同
    array<int, 3> arr3{7, 8, 9};
    arr2.swap(arr3);
    cout << "after swap" << endl;
    print_array(arr2);
    print_array(arr3);


    //非成员函数
    get<0>(arr2) = 100; //访问第一个元素并赋值
    swap(arr2, arr3);   //交换

    return 0;
}
posted @ 2023-05-06 19:23  无形深空  阅读(6)  评论(0编辑  收藏  举报