为什么我选择使用vector,而不是动态数组

我曾经以为动态数组会很快,起码比vector快,然后我在VS2017的编译器试了一下。大家都可以试试。vector肯定针对系统底层的API做优化了,友情提供源代码。

int main()
{
    int n;
    cin >> n;
    int *d = new int[n];
    for (auto i = 0; i < n; ++i)
        d[i] = rand();

    time_t star;

    /* vector<int> a(n);
    star = clock();
    for (auto i = 0; i <n; ++i)
        a[i] = d[i];
    std::cout << clock() - star << endl;

    int *b = new int[n];
    star = clock();
    for (auto i = 0; i < n; ++i)
        b[i] = d[i];
    std::cout << clock() - star << endl;
    delete[] b;
    
    vector<int> c;
    star = clock();
    for (auto i = 0; i < n; ++i)
        c.push_back(d[i]);
    std::cout << clock() - star << endl;

    vector<int> f;
    f.reserve(n);
    star = clock();
    for (auto i = 0; i < n; ++i)
        f.push_back(d[i]);
    std::cout << clock() - star << endl;

    delete[] d; */
    int **b = new int *[n];
    for (auto i = 0; i < n; ++i)
        b[i] = new int[n];
    star = clock();
    for (auto i = 0; i < n; ++i)
        for (auto j = 0; j < n; ++j)
            b[i][j] = d[i] * d[i] + 1;
    std::cout << clock() - star << endl;
    for (auto i = 0; i < n; ++i)
        delete[] b[i];
    delete[] b;

    vector<vector<int>> a(n);
    for (auto &t : a)
        t.resize(n);
    star = clock();
    for (auto i = 0; i < n; ++i)
        for (auto j = 0; j < n; ++j)
            a[i][j] = d[i] * d[i] + 2;
    std::cout << clock() - star << endl;

    int **p = (int **)malloc(n * sizeof(int *));
    for (auto i = 0; i < n; ++i)
        p[i] = (int *)malloc(n * sizeof(int));
    star = clock();
    for (auto i = 0; i < n; ++i)
        for (auto j = 0; j < n; ++j)
            p[i][j] = d[i] * d[i] + 3;
    std::cout << clock() - star << endl;
    for (auto i = 0; i < n; ++i)
        free(p[i]);
    free(p);
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值