c++ array

定义

c++11添加了数组 array, 使用它需要包含 <array> 头文件,定义为:

template<typename _Tp, std::size_t _Nm>
struct array

优点

array不会像c语言中的数组一样会退化成T*。

#include <iostream>
#include <array>

using namespace std;


void func(array<int, 8> & a)
{
    cout << sizeof(a) << endl;
}

int main()
{
    array<int, 8> a;

    cout << sizeof(a) << endl;

    func(a);

    return 0;
}

输出:

32
32

array 具有C风格的数组的优点,比如能够随机访问、知道大小、赋值,同时,支持C++容器的部分功能

缺点

默认情况下,array中的元素值是随机的

不像vector容器,array的swap操作时间复杂度是 O(N)

#include <iostream>
#include <array>
#include <algorithm>

using namespace std;


int main()
{
    array<int, 8> a;

    for (int & e : a)
    {
        cout << e << endl; // 内部是随机值
    }

    a.fill(6);  // 全部赋值为6

    cout << a.size() << ' ' << a.max_size() << endl; // 8 8
    for_each(a.begin(), a.end(), [](int & i) {    // 遍历
        cout << i << ' ';
    });

    a.begin();
    a.end();
    a.cbegin();
    a.cend();
    a.rbegin();
    a.rend();
    a.crbegin();
    a.crend();

    cout << *a.data() << endl;
    cout << a.front() << ' ' << a.back() << endl;
    int *p = a.data();

    array<int, 8> b;

    a == b;
    a != b;
    a < b;

    cout << get<7>(a) << endl;

    return 0;
}

 

原文链接: https://www.cnblogs.com/zuofaqi/p/10210480.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    c++ array

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/287889

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月15日 上午10:29
下一篇 2023年2月15日 上午10:30

相关推荐