简体   繁体   中英

Passing a vector by reference and changing its values in a range-based for loop?

I'm trying to change the values of a vector by doing something similar to the following function:

vector<int> Question2_Part3(vector<int> &v){

    for(auto elem : v){
        elem *= 2;
        cout << elem << " ";
    }
    cout << "\n" << endl;

    return v;
}

Is this possible? I know that in my for loop, it is the value of elem that is changing. Can I have the same output while also changing the values in v and still use a range-based for loop?

Yes it is possible but use a reference

for (auto &elem : v) {
    elem *= 2;
    cout << elem << " ";
}

This is also more efficient as it avoids copying each vector element to a variable. Actually if you didn't want to change the elements you should do

for (const auto &elem : v) {
    cout << elem << " ";
}

More details

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM