2个关于C++字符串指针程序的区别

mosoft521 2009-01-18 08:12:22
C++ Primer第四版
ex5-18a.cpp

//定义一个vector对象,其每个元素都是指向string类型的指针
//读取该vector对象,输出每个string的内容及其长度
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<string*> spvec;
string str;
cout<<"Enter some strings(Ctrl+Z to end)"<<endl;
while(cin>>str)
{
string *pstr=new string;
*pstr=str;
spvec.push_back(pstr);
}
//输出每个string的内容及其长度
vector<string*>::iterator it=spvec.begin();
while(it!=spvec.end())
{
cout<<**it<<" "<<(**it).size()<<endl;
++it;
}
cout<<sizeof spvec<<endl;
it=spvec.begin();
while(it!=spvec.end()){
delete *it;
++it;
}
system("PAUSE");
return 0;
}


ex5-18b.cpp

//定义一个vector对象,其每个元素都是指向string类型的指针
//读取该vector对象,输出每个string的内容及其长度
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<string> svec;
string str;
cout<<"Enter some strings(Ctrl+Z to end)"<<endl;
while(cin>>str)
{
svec.push_back(str);
}
//输出每个string的内容及其长度
vector<string>::iterator it=svec.begin();
while(it!=svec.end())
{
cout<<*it<<" "<<(*it).size()<<endl;
++it;
}
cout<<sizeof svec<<endl;
system("PAUSE");
return 0;
}


问题一:
我理解2个vector里存放的东西是不一样的,a程序里的vector里放的是指针,而b程序里放的是string
为何我输入pad pad pad,2个程序都输出sizeof为12?很怪异的
后来我以为3个指针也是12字节,即每个指针占4字节=32位,符合我的32位机地址
我又输入abcdefg abcdefg abcdefg,2个程序还是都输出sizeof为12?还是不对
难道vector中存放的是字符串指针?而不是实际内容?强的
请看过vector源代码的高人解答
暂时只有问题一.
...全文
355 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
waizqfor 2009-01-18
  • 打赏
  • 举报
回复
LZ仔细看看sizeof的概念问题 sizeof计算的是类型的字节大小 跟你vector中存储什么类型的数据是没有关系的 只计算vector的字节长度
hackers007 2009-01-18
  • 打赏
  • 举报
回复
好比int a;
sizeof(a),就是sizeof(int)
hackers007 2009-01-18
  • 打赏
  • 举报
回复
这里的sizeof统计的是对象vector的大小
因为vector类型的大小为12,所以不论你传什么都是一样的,详细的参考深入C++对象模型
sagegz 2009-01-18
  • 打赏
  • 举报
回复
富农结帖率0...

65,210

社区成员

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

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