Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 432
KOB Avatar asked Nov 03 '15 20:11

KOB


People also ask

How do you access a vector element from a for loop?

Use a for loop and reference pointer In C++ , vectors can be indexed with []operator , similar to arrays. To iterate through the vector, run a for loop from i = 0 to i = vec. size() .

What is a range based for loop?

Range-based for loop in C++ Range-based for loop in C++ is added since C++ 11. It executes a for loop over a range. Used as a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in a container.

Does range based for loop use iterator?

Range-Based 'for' loops have been included in the language since C++11. It automatically iterates (loops) over the iterable (container).

What is the difference between for range loop and?

The difference between a for loop and a range based for loop is roughly analogous to the difference between goto and a for loop. Former is a more generic control flow, while the latter is more structured. Every range based loop can be written as a for loop and every for loop can be written as a goto.


1 Answers

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

like image 144
Manos Nikolaidis Avatar answered Sep 30 '22 08:09

Manos Nikolaidis