+ 1

Output of C++ code

Can someone explain this C++ code? https://code.sololearn.com/cdRICRoQ28tU/#cpp

9th Oct 2020, 4:09 PM
Edward Finkelstein
Edward Finkelstein - avatar
6 Respuestas
+ 3
That's a special for loop used for arrays..(edit : vector, map,... A collection of iterable types) Syntax is for( type variable : array) { ... } Variable is assigned array value in sequence from index 0 to length-1 in each next iterations.. Like a normal for loop. But in first loop, int i = a; is normal assignment a also variable. But int &i =a ; is assigning address of a in address of i so now I and a will point to same locations so change in one variable will change in other variables also... So in first loop change in i will replect back to array value. So that's why array values also changing.. Edit : Arsenic I specified relating to code specific only.. (In that code) Ok. C++ has vectors and map also.. So if it misleading, I edit it. It works for any collection of elements type.. Ex: array, vector.. Done.. 👍
9th Oct 2020, 6:25 PM
Jayakrishna 🇮🇳
+ 3
You are using 2 ranged based *for* loops here :- The first one is traversing the entire array and is reducing the ACTUAL values in it by 1 The second one is just displaying each value of array.
9th Oct 2020, 4:33 PM
Arsenic
Arsenic - avatar
+ 2
Jayakrishna🇮🇳 it's not specific for arrays. It is a ranged based loop which can be used to iterate over any range of values, for example std::vector , std::map or any other C++ Standard Library sequence whose range is defined by a begin() and end() Edward Finkelstein have a look at this 👇 to learn more about ranged based *for* loops in C++ https://docs.microsoft.com/en-us/cpp/cpp/range-based-for-statement-cpp
10th Oct 2020, 12:40 AM
Arsenic
Arsenic - avatar
+ 1
thank you Arsenic!
10th Oct 2020, 4:40 PM
Edward Finkelstein
Edward Finkelstein - avatar
0
what do the : and the & symbol do?
9th Oct 2020, 5:43 PM
Edward Finkelstein
Edward Finkelstein - avatar
0
thank you Jayakrishna!
9th Oct 2020, 6:50 PM
Edward Finkelstein
Edward Finkelstein - avatar