Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

c++ - 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 << "
" << 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...