for (int i = 0; i

gauldoth 2011-04-21 11:34:16
有问题么?
...全文
679 14 打赏 收藏 转发到动态 举报
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
用下size_t会死吗,还是我无知?
hongwenjun 2011-04-21
  • 打赏
  • 举报
回复
#include <iostream>
#include <vector>
#include <string>
#include <limits.h>

using namespace std;

int main()
{
string str("size_t 和 int 区别");
cout << str <<endl;
cout << str.size() <<endl;
cout << str.max_size()<<endl;
cout << INT_MAX <<endl;

return 0;
}
输出内容:
size_t 和 int 区别
18
1073741820
2147483647


看来 在 windows下 int 代替 size_t 一般没问题
gauldoth 2011-04-21
  • 打赏
  • 举报
回复
复数是啥?
好象有些理解了。
这里用int和用unsigned int效果是一样的吧?只要size()返回的是unsigned int,无论多大,用int都能正常遍历所有元素吧?
無_1024 2011-04-21
  • 打赏
  • 举报
回复
不用复数是不会出问题的
size_t一般等价于unsigned int
gauldoth 2011-04-21
  • 打赏
  • 举报
回复
因为size_t超麻烦啊。。
我多是用int。。
还有我看到这句,有点晕。
Yes, I know that I could declare i to be a vector<double>::size_type rather than plain int to quiet warnings from some hyper-suspicious compilers, but in this case,I consider that too pedantic and distracting.
無_1024 2011-04-21
  • 打赏
  • 举报
回复

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main()
{

string str("sadfsdfgfhf");
for( int i = 0;i < str.size(); i++ )
{
cout << str[i] << endl;
}
vector<int> v(10,5);
for( int j = 0;j < v.size(); j++ )
{
cout << v[j] << endl;
}
return 0;
}


gauldoth 2011-04-21
  • 打赏
  • 举报
回复
v随便什么容器。
vector之类都行。
这里是要问用int会不会出问题?
还是要用size_t?
無_1024 2011-04-21
  • 打赏
  • 举报
回复

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main()
{

string str("sadfsdfgfhf");
for( int i = 0;i < str.size(); i++ )
{
cout << str[i] << endl;
}
return 0;
}


c_losed 2011-04-21
  • 打赏
  • 举报
回复
v是容器?
ms不是这么用的。。。
無_1024 2011-04-21
  • 打赏
  • 举报
回复
v是什么类型?
gauldoth 2011-04-21
  • 打赏
  • 举报
回复
谢谢楼上几位。
用!=判断,这个学到了。
有次我就写出象下面类似的代码,

for(size_t i = v.size()-1; i >= 0; i--)
{
//...
}

结果肯定是悲剧了。。
可移植之类的暂时考虑不到。。没到那高度。。
谢谢,结帖撒。
一根烂笔头 2011-04-21
  • 打赏
  • 举报
回复
但从 语句 上说没啥问题啊!用词很恰当,表达很贴切!
qq120848369 2011-04-21
  • 打赏
  • 举报
回复
楼主是不是怕出现死循环情况,size_t的确有一个容易出问题的情况,就是如下情况:

for(size_t i=0;i-1>=0;++i)
{}

像这种情况,如果是int的话,循环会因为i-1=-1<0而终止。
而size_t的话,i-1已经溢出得到一个很大的正数,所以循环始终结束不了。因为其实size_t怎么样都是>=0的,所以结束不了。

用size_t通常的建议都是使用!=做循环判断,如果需要使用不等号,才使用int.
shexinwei 2011-04-21
  • 打赏
  • 举报
回复
 在C++中,size_t的引入增加了程序在不同平台上的移植性,经测试发现,在32位系统中size_t是4字节的,而在64位系统中,size_t是8字节的,这样利用该类型可以增加程序移植性。

64,649

社区成员

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

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