C++ string使用for改变为何必须使用引用
例子1:
#include <iostream>
#include <cctype>
using std::cin;
using std::cout;
using std::endl;
using std::string;
int main(){
string s("assss,ddd,eeee");
decltype(s.size()) punct_cnt = 0;
for(auto c : s){
if(ispunct(c)){
++punct_cnt;
}
}
cout << punct_cnt << endl;
}
一个普通的遍历字符串,输出标点符号值为2
例子2:
当改变std::string 中的值
错误代码:
#include <iostream>
#include <cctype>
using std::cin;
using std::cout;
using std::endl;
using std::string;
int main(){
string s("assss,ddd,eeee");
decltype(s.size()) punct_cnt = 0;
for(auto c : s){
c = toupper(c);
}
cout << s << endl;
}
输出assss,ddd,eeee
正确代码:
#include <iostream>
#include <cctype>
using std::cin;
using std::cout;
using std::endl;
using std::string;
int main(){
string s("assss,ddd,eeee");
decltype(s.size()) punct_cnt = 0;
for(auto &c : s){
c = toupper(c);
}
cout << s << endl;
}
输出ASSSS,DDD,EEEE
结论:如果要改变string中对象的字符的值,必须把循环变量定义成引用类型,如果是直接=,只是对原先对象的拷贝(即值的传递)。而想要去改变原始值,就要去获得其原始对象,所以使用引用。
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: PHP获取数组的键与值
- 下一篇: C++引用类型