0004.容器之vector

#include<iostream>                                                                                                                                                                                                  
#include<vector>
#include<stdexcept>
#include<string>
#include<cstdlib>//abort()
#include<cstdio>//snprintf();整数转字符
#include<ctime>
#include<algorithm>
#include<array>
#include<string>
using namespace std;

#define NUM 100

int main()
{
    vector<string> c;
    char buf[10];
    clock_t timeStart = clock();

    for (long i = 0; i < NUM; ++i)
    {
        try
        {
            snprintf(buf,10,"%d",rand());
            c.push_back(string(buf));
        }
        catch (exception& p)
        {
            cout << "i=" << i << p.what() << endl;
            abort();
        }
    }
    string target = c[23];

    cout << endl;
    cout << "毫秒: " << (double((clock() - timeStart))/CLOCKS_PER_SEC * 1000 )<< endl;
    cout << "vector.size(): " << c.size() << endl;//
    cout << "vector.front(): " << c.front() << endl;
    cout << "vector.back(): " << c.back() << endl;
    cout << "vector.data(): " << c.data() << endl;
    cout << "vector.cappacity() : " << c.capacity() << endl;
    cout << "tareg: " << target << endl;
    cout << endl;

    cout << "---------普通查找开始---------" << endl;
    timeStart = clock();

    auto iterItem = ::find(c.begin(),c.end(),target);
    cout << "耗时: " << (double((clock() - timeStart))/CLOCKS_PER_SEC * 1000 )<< endl;
    if (iterItem != c.end())//此测试程序必定成功
    {
        cout << "值为: " << *iterItem << endl;
    }
    cout <<"--------普通查找结束----------" << endl;
    cout << endl;

    timeStart = clock();
    cout << "----------排序开始------------" << endl;

    sort(c.begin(),c.end(),[=](string a, string b){
            int i = stoi(a);
            int j = stoi(b);
            return i>j;//降序
            });
#if 0
    for (size_t i = 0; i < c.size(); ++i)
    {
        cout << c[i] << endl;
    }
#endif
    cout << "----------排序结束------------" << endl;

    string* pItem = (string*)bsearch(&target,c.data(),c.size(),sizeof(string),[=](const void* a, const void* b){
            string* stra = (string*)a;
            string* strb = (string*)b;
            int bi = stoi(*stra);
            int bj = stoi(*strb);
            return j-i;
            });

    cout << *pItem << endl;

    return 0;
}

输出如下:

注意:在此测试中,发现升序和降序时,使用bsearch比对函数必须要有所不同,否则无法查找目标值;升序:return bi - bj; 降序: return bj - bi;

posted @ 2023-03-24 20:56  test369  阅读(8)  评论(0编辑  收藏  举报