侯捷C++STL 体系结构与内存分析:容器vector测试

本文详细探讨了C++ STL中的vector容器,通过侯捷老师的测试程序,分析了vector的内存使用情况及其性能表现,揭示了vector在不同操作下的内部工作机制。
摘要由CSDN通过智能技术生成

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;
		}
	}
}

侯捷老师测试的结果
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值