C++ 的string最多能容纳多少个字符

clayXmore 2012-05-06 06:33:38
如题!
...全文
12323 15 打赏 收藏 转发到动态 举报
写回复
用AI写文章
15 条回复
切换为时间正序
请发表友善的回复…
发表回复
David_xtd 2013-07-31
  • 打赏
  • 举报
回复
1073741820对应到十六进制是0x3FFFFFFC, 而string本身的长度为4, 所以,单个string所占的空间最大可为0x40000000, 该数值为int的一半,不知为什么不是int的最大值。
David_xtd 2013-07-31
  • 打赏
  • 举报
回复
#include <iostream> #include <string.h> namespace { using namespace std; } int main() { string str = "0123456789"; cout << "sizeof(str) is: " << sizeof(str) << endl; cout << "size of str is: " << str.size() << endl; cout << "maxsize of str is: " << str.max_size() << endl; cout << "capacity of str is: " << str.capacity() << endl; cout << "================================================================================" << endl; return 0; } 环境:ubuntu 12.04 desktop,g++ Version 4.6.3,编译后运行的结果: u1204@u1204-zhw:~/wrk/tmp/cpp_src/cpp_exer$ ./test_string_op sizeof(str) is: 4 size of str is: 10 maxsize of str is: 1073741820 capacity of str is: 10 ================================================================================ u1204@u1204-zhw:~/wrk/tmp/cpp_src/cpp_exer$ 就是说最大字符长度只能为1073741820,不知道为什么会这样。
zO_Oz 2012-05-07
  • 打赏
  • 举报
回复
你去看看string是怎么封装的。
Scorpiour 2012-05-07
  • 打赏
  • 举报
回复 1
一般来说百万长度的string(一部英文小说)还是很轻松的……
luotuo44 2012-05-07
  • 打赏
  • 举报
回复
size_t类型能表示的最大值。4294967295
xdhxt 2012-05-07
  • 打赏
  • 举报
回复
同意5楼
firendlys 2012-05-07
  • 打赏
  • 举报
回复
如果字符串长度达到G的级别,还要注意一下你的内存是否足够。
一般来说,32位程序每个进程(不论是32位系统还是64位系统)最多只能使用2G内存(据说开启3GB模式,可以最多使用3G内存),就是说,即使string最大可以达到4G的容量,但由于系统限制,你永远无法使用那么多。
「已注销」 2012-05-07
  • 打赏
  • 举报
回复
size_type __CLR_OR_THIS_CALL max_size() const
{ // return maximum possible length of sequence
size_type _Num = _Mybase::_Alval.max_size();
return (_Num <= 1 ? 1 : _Num - 1);
}
max_size的实现是上面的,是最大值unsigned int-1;所以结果是4294967294,但可能string的长度比这个值还要大些
[Quote=引用 5 楼 的回复:]
如果内存够,std::string容纳6百万个字符就没问题。
std::string库有一个成员函数max_size,可以用来获得最大字符长度。
下面这段代码在我的机器上输出4294967294,其实就是signed int的最大值。


C/C++ code


#include <string>
#include <iostream>

using namespace s……
[/Quote]
taodm 2012-05-06
  • 打赏
  • 举报
回复
才6M,为啥自己不编段程序试一下?
clayXmore 2012-05-06
  • 打赏
  • 举报
回复
OK 谢谢!
northcan 2012-05-06
  • 打赏
  • 举报
回复
如果内存够,std::string容纳6百万个字符就没问题。
std::string库有一个成员函数max_size,可以用来获得最大字符长度。
下面这段代码在我的机器上输出4294967294,其实就是signed int的最大值。


#include <string>
#include <iostream>

using namespace std;

int main()
{
string s;
cout << s.max_size() << endl;

return 0;
}
clayXmore 2012-05-06
  • 打赏
  • 举报
回复
就6MB的样子吧!
clayXmore 2012-05-06
  • 打赏
  • 举报
回复
6百万可以吗?
muyi66 2012-05-06
  • 打赏
  • 举报
回复
string里有一个容量字段,还有个串长字段。在VS里都是32位的。如果没给别的限制,那就是说,弄个1、2个G也是可以的。不过,字符串有这么长的吗?
muyi66 2012-05-06
  • 打赏
  • 举报
回复
没试过,估计几万字符毛毛雨。

64,646

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧