+ 2
Why this not work? Can someone explain for me?
i've tried this code on code block but it wasn't work. I have took it in the question and sololearn give me an answer that i didn't understand https://code.sololearn.com/c9sPmA5DoTr9/?ref=app
18 Antworten
+ 15
https://code.sololearn.com/c04iuEn9x0O8/?ref=app
+ 15
perhaps you should study iterators first, before range based for loops
https://www.cprogramming.com/tutorial/stl/iterators.html
+ 14
Good question! I have never tried nor thought of this before.
The variable y should be initialised in the range for loop, as it is local to the loop only.
so. it must be in the form of:
for(dataType name : container) { }
so for your case it should be
for(int y : x) {}
+ 13
? I am not sure, but my guess is because the compiler can't deduce the appropriate method of initialisation?
-- @Sreejith: the y part is just a named variable of the same type of that inside the container.
+ 13
no, the error occurs before the switch statement.
+ 11
@alex you are correct! use of the auto keyword is preferable. But if the type is known using it can be used :)
+ 11
@Sreejith: I don't know python well enough to confirm with much accuracy, but on the surface looking at the syntax, yes
+ 2
but i don't understand for( int y: x). Does it mean x[y] ??
+ 2
And after the link Jay posted take a look at this:
https://www.cprogramming.com/c++11/c++11-ranged-for-loop.html
That's an explanation of the range based for loop
+ 1
missing semicolon after int y
line no 4
+ 1
oh sorry but i'm sure that i've got it on my computer but it still not work
+ 1
why can't we just use scope resolution operator here
+ 1
#include <iostream>
using namespace std;
int x[10]={1,2,3,4,5,6,7,8,9,10};
int main() {
for(auto y : x){
switch(y){
case 1: cout<<"c";
break;
case 2: cout<<"p";
break;
case 3: cout <<"p";
break;
case 4: cout<<"!";
break;
}
}
return 0;
}
+ 1
oh you have a break in case function
+ 1
but in the question of this don't have. Could it be a cause
+ 1
Yes in that case you need breaks.
Without break everything below of the entry point will also be executed. This can be handy sometimes, but in most cases you need them.
Without break the output would be:
1st loop: cpp!
2nd loop: pp!
3rd loop: p!
4th loop: !
-> cpp!pp!p!!
+ 1
so its kind of like
arr="Hello"
for x in arr:
right??
0
yes. It also works with int y