问题
include <iostream>
#include <vector>
using namespace std;
int main(){
string str="hello world";
vector<char> res;
for(unsigned i = str.size()-1; i >= 0; i--){
res.push_back(str[i]);
}
for(unsigned i=0;i<res.size();i++){
cout<<res[i];
}
return 0;
}
输出结果:

解决办法:
将第一个for循环的unsigned换成int
for(int i = str.size()-1; i >= 0; i--){
res.push_back(str[i]);
}

原因:暂时没有找到原因,猜测是string对[]运算符重载时的写法导致。
本文通过一个C++字符串反转的代码实例,展示了当使用unsigned变量作为循环计数器时可能出现的问题,并提供了解决方案。文章指出,将unsigned类型更改为int可以避免潜在的错误,但未深入探讨其根本原因。
2624

被折叠的 条评论
为什么被折叠?



