c++11 auto 與auto& 遍歷vector區別


說明

轉載請注明出處:https://www.cnblogs.com/bllovetx/p/11669320.html
歡迎訪問My Home Page
--2019.11.21

c++11 auto 與auto& 遍歷區別

今天被這個問題坑了一天,一直以為是算法錯了,debug了一天,最后暴力生成數據才發現,測試代碼如下:

➜  test vim test.cpp
➜  test g++ test.cpp -o test
➜  test ./test              
original: 6610
auto: 6610
auto&: 1234
➜  test cat test.cpp 
#include<bits/stdc++.h>
using namespace std;
struct node{
        int i;
        string w;
};
int main(){
        vector<node>ns;
        ns.clear();
        ns.push_back({1,"6610"});
        cout<<"original: "<<ns[0].w<<endl;
        for(auto it:ns)it.w="1234";
        cout<<"auto: "<<ns[0].w<<endl;
        for(auto &it:ns)it.w="1234";
        cout<<"auto&: "<<ns[0].w<<endl;
}

區別顯而易見,可讀和可寫。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM