nest for-each loop?

I am experimenting with different arrays - by pointer, arrays with subscripts, etc. I am curious wether a for-each loop can be nested. I would ideally like the outer "loop" to go from 1 to 4 and the inner from 1 to 12. I have a skeleton framework and really don't know how to proceed, partly because I don't know whether it can be done.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include<iostream>
#include<array>

using namespace std;

struct Elements
{
	int x;
	int y;
};

int main()
{
	//nested pointer?
		array<Elements,52>cards;
		for(Elements&cards_ref:cards)
		{
			for(Elements &cards_ref:cards)
			{
				{;}
			}
		}

		return 0;
	}


Last edited on
Your question doesn't really make sense. Elements doesn't have any containers so your inner loop doesn't make sense.

What exactly are you trying to accomplish?





You are adding complexity.

I hope you have numbered your cards modulo 13, such that 1..13 is suit 1, 14..26 is suit 2, etc.
Hence, all you need are some functions to convert between an index and a (suit, rank) pair:

(This presumes the standard 52-card French deck.)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int card_to_index( int suit, int rank )
{
  return (suit * 13) + rank;
}

int index_to_suit( int index )
{
  return index / 13;
}

int index_to_rank( int index )
{
  return index % 13;
}

When you encode the card index like this, it automatically works in the same way:

1
2
3
4
5
6
7
8
9
10
11
12
const char* suits[] =
{
  "Clubs",
  "Hearts",
  "Diamonds",
  "Spades"
};

for (unsigned n = 0; n < cards.size(); n++)
{
  cout << "The " << (index_to_rank(n)+1) << " of " << suits[index_to_suit(n)] << " is at (" << cards[n].x << "," << cards[n].y << ")\n";
}
Alternately:

9
10
11
12
13
14
unsigned n = 0;
for (Elements& position : cards)
{
  cout << "The " << (index_to_rank(n)+1) << " of " << suits[index_to_suit(n)] << " is at (" << position.x << "," << position.y << ")\n";
  n += 1;
}

Hope this helps.
It does. Thx for taking y our time to write that.
Topic archived. No new replies allowed.