首页 > 编程语言 > 详细

C++中的auto的使用

时间:2019-03-09 19:30:19      阅读:142      评论:0      收藏:0      [点我收藏+]

需要改变迭代对象 for(auto &i:s)

string s = "hello";
for (auto &i : s ) 
    i = toupper(i); //改变成大写,影响s的值
cout<<s<<endl; //s的值是 HELLO

不需要改变迭代对象 for(auto i:s)

string s = "hello";
for (auto i : s )
    i = toupper(i); //改变成大写,不影响s的值
cout<<s<<endl; //s的值是 hello

迭代map

#include <iostream>
#include <map>

using namespace std;

int main() {
    map<int,string> student;
    student.insert(pair<int,string>(2,"li"));
    student.insert(pair<int,string>(1,"wang"));
    student.insert(pair<int,string>(3,"sun"));
    for(auto &v : student) // for(auto v : student)也是可以的
        cout<<"key: "<<v.first<<" | value: "<<v.second<<endl;
    return 0;
}

 

C++中的auto的使用

原文:https://www.cnblogs.com/dongdong25800/p/10502542.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!