为什么是string::size_type而不是int?---顺便聊聊无符号数和负数的比较
2015-03-21 11:18
337 查看
我们先看下面的程序(假设某环境下, 用16位表示整形):
需要改为:
所以, 还是养成好习惯吧。
最后, 我们来欣赏这样一个小程序(一定要小心无符号数和负数的相互作用):
ok, 先这样。
#include <iostream> #include <string> #include <cmath> using namespace std; int main() { int a = pow(2, 15) - 1; // 假设某环境下, 用16位表示整形 cout << a << endl; // a是最大的int值 string s(a, 'x'); cout << s << endl; s += "test"; // ok, 此时s的长度超出了整形的最大值a int i = 0; for(i = 0; i < s.size(); i++) // 死循环 { cout << s[i]; } cout << endl << "end" << endl; return 0; }
需要改为:
#include <iostream> #include <string> #include <cmath> using namespace std; int main() { int a = pow(2, 15) - 1; // 假设某环境下, 用16位表示整形 cout << a << endl; // a是最大的int值 string s(a, 'x'); cout << s << endl; s += "test"; // ok, 此时s的长度超出了整形的最大值a string::size_type i = 0; for(i = 0; i < s.size(); i++) // ok { cout << s[i]; } cout << endl << "end" << endl; return 0; }
所以, 还是养成好习惯吧。
最后, 我们来欣赏这样一个小程序(一定要小心无符号数和负数的相互作用):
#include <iostream> #include <string> using namespace std; int main() { if(strlen("abc") < -1) { cout << "yes1" << endl; // 到这个分支 } else { cout << "no1" << endl; } if(sizeof("abc") < -1) { cout << "yes2" << endl; // 到这个分支 } else { cout << "no2" << endl; } if(string("abc").size() < -1) { cout << "yes3" << endl; // 到这个分支 } else { cout << "no3" << endl; } return 0; }
ok, 先这样。
相关文章推荐
- size_type和int为什么不能直接比较
- 无符号整数(string::size_type,size_t,unsigned,long unsigned)
- scala中为什么针对array和string的长度计算推荐size,而不是length
- std::vector<std::string>::size_type和 int的区别
- shiro-密码比较的设计 CredentialsMatcher -为什么Java中的密码优先使用 char[] 而不是String?
- C++ Primer --- string::size_type
- java中的String为什么可以使用==比较字符串内容?
- 今天比较STRING和INT,很奇怪
- string::size_type类型
- c语言int to string一个比较经典得算法
- 为什么INT_MIN不是直接写成-2147483648
- C++ Primer --- string::size_type
- 在C#中,string 类型可与SQL SERVER中的int 类型作比较
- 关于string::size_type
- 将string变为int 的几种方法方法比较
- groovy string类型转换成int(来自csdn)不要问为什么系列6
- C++ 中string::size_type相关问题
- string::size_type 是什么定义类型?
- 利用write(int)方法写入一个int型的数据为什么看见的却不是整形的数据?
- string::size_type - what is this?