As in title, is there any kind of "foreach" equivalent for arrays, or its just for vectors? I've already asked a computer science professor and he answered it only for more complex structures, none of the ones we'll see in the course.
-
2@timrau: Ermmmm not really?!Lightness Races in Orbit– Lightness Races in Orbit2015-04-20 17:15:15 +00:00Commented Apr 20, 2015 at 17:15
-
The question I proposed as duplicate itself is indeed the answer to this question.timrau– timrau2015-04-20 17:27:01 +00:00Commented Apr 20, 2015 at 17:27
-
@timrau: Not really, no.Lightness Races in Orbit– Lightness Races in Orbit2015-04-20 17:28:26 +00:00Commented Apr 20, 2015 at 17:28
-
Yeah, it's more or less the same; mine is more generic...bertof– bertof2015-04-21 07:50:56 +00:00Commented Apr 21, 2015 at 7:50
Add a comment
|
4 Answers
Your professor is wrong.
int array[] = {0, 1, 2, 3};
for (int& x : array)
x *= 2;
// Array now looks like:
// {0, 2, 4, 6}
(live demo)
4 Comments
Tomas Kubes
I wouldn't call him wrong, just outdated. The school was always few years/decades after the edge.
Lightness Races in Orbit
@qub1n: That makes him wrong at time of writing. He might have been right had he made that claim five years ago (modulo
BOOST_FOREACH, anyway), but that is not the operative scenario here. I might as well tell you that C++ hasn't been invented yet; you're going to say I'm not wrong?Tomas Kubes
No, because If it hasn't been invented, you couldn't have known that it is called C++ and thus you are wrong :-) Don't take it too much logically, it is kind of respect to professor to call him rather outdated then wrong.
Lightness Races in Orbit
@qub1n: I'd have more respect for him if he actually knew his craft rather than spreading misinformation to defenceless students.
The possible duplicate use vector example or C array example. To precisely answer the question, I can told use yes, in C++11 it is possible, but you should better use std::array.
//use std::array notation, it is just wrapper over what you know as C Array
std::array<int, 3> a3 = {1, 2, 3};
And iterate it like this:
for(const auto& s: a3)
std::cout << s << ' ';
There exists something like Microsoft C++ foreach, but you can consider deprecated, because of C++11 features in this example.