#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;
标签:0004,容器,cout,降序,vector,升序,include,buf From: https://www.cnblogs.com/gom-linwei/p/17253336.html