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?
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() .
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.
Range-Based 'for' loops have been included in the language since C++11. It automatically iterates (loops) over the iterable (container).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With