c++ std string reserve 测试

#include "windows.h"
#include <tchar.h>
#include <cstdio>
#include <string>
#include <limits>

using namespace std;

/*
//z 2014-04-10 11:54:59 BG57IV3@XCL T1688293017.K.F1288753923[T13,L274,R5,V285]
输出结果,观察数据可见其策略。

可见一般情况下实际 reserve 的 capacity 比 申请的要大,当大于某个数值之后,变成逐个增加了,而且由于申请的内存巨大,非常消耗资源。

15
31
47
70
105
157
235
352
528
792
1188
1782
2673
4009
6013
9019
13528
20292
30438
45657
68485
102727
154090
231135
346702
520053
780079
1170118
1755177
2632765
3949147
5923720
8885580
13328370
19992555
29988832
44983248
67474872
101212308
151818462
227727693
341591539
512387308
512387309
768580963
768580964
768580965
768580966
768580967
768580968
768580969
768580970
*/
void Test_String_Reserve()
{
	string str;
	TCHAR buff[16] = {'\0'};
	size_t nCapacity = str.capacity();

	int intMax = (std::numeric_limits<int>::max)();
	for (int i = 1 ; i < intMax ;++i)
	{
		str.reserve(i);
		if(nCapacity!=str.capacity())
		{
			_stprintf(buff,_T("%d"),nCapacity);
			OutputDebugString(buff);
			nCapacity = str.capacity();
		}
	}

	_stprintf(buff,_T("%d"),nCapacity);
	OutputDebugString(buff);
}

int _tmain(int argc, _TCHAR* argv[])
{
	Test_String_Reserve();

	return 0;
}

//z 2014-04-10 11:54:59 BG57IV3@XCL T1688293017.K.F1288753923[T13,L274,R5,V285]

/*
输出:
从大往小reserve,可见一般一直保留不变,直到n小于等于15。由于采取了优化的措施(通常保留 capacity 不变),这部分运行较快。
//z 2014-04-10 12:05:54 BG57IV3@XCL T3063169329.K.F1288753923[T14,L328,R5,V286]
768580975
15
*/
void Test_String_Reserve_2()
{
	string str;
	const int nReserve = 768580964;
	str.reserve(nReserve);
	TCHAR buff[16] = {'\0'};
	size_t nCapacity = str.capacity();

	//int intMax = (std::numeric_limits<int>::max)();
	for (int i = nReserve ; i > 0 ;i-=15)
	{
		str.reserve(i);
		if(nCapacity!=str.capacity())
		{
			_stprintf(buff,_T("%d"),nCapacity);
			OutputDebugString(buff);
			nCapacity = str.capacity();
		}
	}

	_stprintf(buff,_T("%d"),nCapacity);
	OutputDebugString(buff);
}

//z 2014-04-10 13:47:04 BG57IV3@XCL T2734643987.K.F1288753923[T17,L426,R8,V350]
/*
输出:
win7 x64 (visual studio 2005 | win32 build)
4294967294 //z maxsize
4294967295 //z unsigned int::max value
*/
void GetStringMaxSize()
{
	TCHAR buff[16] = {'\0'};
	string str;
	size_t nMaxSize = str.max_size();

	_stprintf(buff,_T("%u"),nMaxSize);
	OutputDebugString(buff);

	unsigned int nMax = (std::numeric_limits<unsigned int>::max)();
	_stprintf(buff,_T("%u"),nMax);
	OutputDebugString(buff);
}


转载于:https://www.cnblogs.com/IS2120/p/6745673.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值