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.
Asked
Active
Viewed 414 times
1
-
2@timrau: Ermmmm not really?! – Lightness Races in Orbit Apr 20 '15 at 17:15
-
The question I proposed as duplicate itself is indeed the answer to this question. – timrau Apr 20 '15 at 17:27
-
@timrau: Not really, no. – Lightness Races in Orbit Apr 20 '15 at 17:28
-
Yeah, it's more or less the same; mine is more generic... – bertof Apr 21 '15 at 07:50
4 Answers
5
Yes, you can use algorithms like for_each
, or range-based for loops, with arrays, as well as any other container:
int a[] = {1,2,3,4,5};
for_each(begin(a), end(a), [](int x){cout << x;});
for (int x : a) cout << x;

Mike Seymour
- 249,747
- 28
- 448
- 644
3
In c++11 and c++14 there is
string[] strarr = {"one","two","three"};
for(string str: strarr)
{
//do stuff
}
But otherwise no. You will either have to use an iterator
or a plain for-loop

Andersnk
- 857
- 11
- 25
1
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)

Lightness Races in Orbit
- 378,754
- 76
- 643
- 1,055
-
I wouldn't call him wrong, just outdated. The school was always few years/decades after the edge. – Tomas Kubes Apr 20 '15 at 17:25
-
1@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? – Lightness Races in Orbit Apr 20 '15 at 17:26
-
1No, 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. – Tomas Kubes Apr 20 '15 at 17:37
-
@qub1n: I'd have more respect for him if he actually knew his craft rather than spreading misinformation to defenceless students. – Lightness Races in Orbit Apr 20 '15 at 17:38
0
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.

Community
- 1
- 1

Tomas Kubes
- 23,880
- 18
- 111
- 148