0003.容器之array测试

#include<array>                                                                                                                                                                                                  
#include<ctime>
#include<cstdlib>//qsort,bsearch,NULL
#include<iostream>
#include<algorithm>
using namespace std;

#define BUF 500000

int main()
{
    array<int,BUF> c;

    clock_t timeStart = clock();

    for (int i = 0; i < BUF; ++i)
    {   
        c[i] = rand();
    }   
    cout << endl;
    cout << "first: " << c[0] << endl;
    cout << endl;

    cout << "毫秒: " << (double((clock() - timeStart))/CLOCKS_PER_SEC * 1000 )<< endl;
    cout << "array.size(): " << c.size() << endl;
    cout << "array.front: " << c.front() << endl;//第一个元素
    cout << "array.back(): " << c.back() << endl;//最后一个元素
    cout << "array.data(): " << c.data() << endl;//地址
    cout << endl;
    int target = c.at(66666);

    cout << "---------------------------普通查找开始------------------------------" << endl;
    timeStart = clock();    
    auto iterItem = ::find(c.begin(), c.end(), target);
    cout << "耗时(毫秒): " << (double((clock() - timeStart))/CLOCKS_PER_SEC * 1000 )<< endl;
    cout << "值为: " << *iterItem << endl;
    cout << "---------------------------普通查找结束------------------------------" << endl;
    cout << endl;

    cout << "-----------------------排序开始---------------------------" << endl;
    timeStart = clock();
    qsort(c.data(), BUF,sizeof(int),[=](const void*a, const void *b){
        return (*(int*)a - *(int*)b);
    });
    cout << "排序耗时-毫秒: " << (double((clock() - timeStart))/CLOCKS_PER_SEC * 1000 )<< endl;
    cout << "排序后第一个元素: " << c[0] << endl;

    cout << "排序后第500个元素: " << c[500] << endl;
    cout << endl;


    cout << "--------------排序后开始查找目标元素:------------------ "<<endl;
    timeStart = clock();
    int* pItem = (int*)bsearch(&target, (c.data()), BUF, sizeof(int),[=](const void* a, const void* b){
        return *(int*)(a) - *(int*)(b);
    });
    cout << "查找元素耗时-毫秒: " << (double((clock() - timeStart))/CLOCKS_PER_SEC * 1000 )<< endl;

    if (pItem)
    {
        cout << "查找成功,值为: " << *pItem << endl;
    }
    else
    {
        cout << "查找失败" << endl;
    }

    cout << endl;

输出如下:

posted @ 2023-03-08 06:56  test369  阅读(10)  评论(0编辑  收藏  举报