vector的测试程序:
#include <vector>
#include <stdexcept>
#include <string>
#include <iostream>
#include <ctime>
#include <cstdio> // snprintf()
#include <cstdlib> // abort()
#include <algorithm>
namespace jj02
{
void test_vector(long& totalCount) //指定多少个元素
{
cout << "\ntest_vector()......... \n";
vector<string> c;
char buf[10];
//srand((unsigned)time(NULL));
clock_t timeStart = clock();
for (long i = 0; i < totalCount; ++i)
{
try { //这边防止内存溢出,string是一个指针大小,而元素是用户指定,可能溢出
snprintf(buf, 10, "%d", rand() % 65535);
c.push_back(string(buf));
} catch(std::exception& e) {
cout << "i=" << i << e.what() << endl;
// 曾经最高 i=58389486 then std::bad_alloc,此时要不到内存(侯老师测试的结果)
abort(); //利用这个方式退出程序
}
}
cout << "milli-seconds:" << (clock() - timeStart) << 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; //vector连续空间的起始点
cout << "vector.capacity()= " << c.capacity() << endl;
string target = get_a_target_string();
{
timeStart = clock();
auto pItem = ::find(c.begin(), c.end(), target); //find模板函数,全局的模板函数,返回的是迭代器,循序查找,可大可小
cout << "::find(), mill-seconds: " << (clock()-timeStart) << endl;
if (pItem != c.end())
cout << "found, " << *pItem << endl;
else
cout << "not found! " << endl;
}
{
timeStart = clock();
sort(c.begin(), c.end());
string* pItem = (string*)bsearch(&target, (c.data()), c.size(), sizeof(string), compareStrings);
cout << "sort()+bsearch(), milli-seconds: " << (clock() - timeStart) << endl;
if (pItem != NULL)
cout << "found, " << *pItem << endl;
else
cout << "not found!" << endl;
}
}
}
侯捷老师测试的结果: