1

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.

4
  • 2
    @timrau: Ermmmm not really?! Commented Apr 20, 2015 at 17:15
  • The question I proposed as duplicate itself is indeed the answer to this question. Commented Apr 20, 2015 at 17:27
  • @timrau: Not really, no. Commented Apr 20, 2015 at 17:28
  • Yeah, it's more or less the same; mine is more generic... Commented Apr 21, 2015 at 7:50

4 Answers 4

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;
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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)

4 Comments

I wouldn't call him wrong, just outdated. The school was always few years/decades after the edge.
@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?
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.
@qub1n: I'd have more respect for him if he actually knew his craft rather than spreading misinformation to defenceless students.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.