1. c++ size_t 和 int 做比较时的问题。
int i = -1;
size_t j = 0;
cout << (j > i ? "j" : "i");
结果输出: i。说明:int型的负数比unsigned型大。所以,在做类似索引循环的时候,一定要注意索引的类型。
比如:
string str("ni hao");
for (size_t i = str.size(); i >= 0; i--)
cout << str[i];
会访问越界。
而此时:
string str("ni hao");
for (int i = str.size(); i >= 0; i--)
cout << str[i];
可以正确输出。
但当询问边界0为size_t/unsigned型时,却会出错。
string str("ni hao");
size_t begin = 0;
for (int i = str.size(); i >= begin; i--)
cout << str[i];
出错原因见最开始的比较。
解决方法:
string str("ni hao");
size_t begin = 0;
for (int i = str.size(); i >= static_cast<int>(begin); i--)
cout << str[i];
2. 有空格输入字符串的时候,不能用cin>>str, 因为cin不能读取空格(空格、tab、换行等),要读取整行包含字符的话,用getline(cin, str)。
3.string 关于[]和at()访问出界的问题:
a. []不进行边界检查,所以出界:
b. at()会进行边界检测,出界时会抛出异常: