std::array member functions

In my code below, can I use .member functions for std::array?

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

using namespace std;

void print_array(std::array<int,52> & deck)
{}; //hold for now...works

int main()
{
	std::array<int, 52> deck;

	int card = 0;
	for (int suit = 0; suit < 5; ++suit) //numbers wrong, prototyping
	for (int rank = 0; rank < 5; ++rank)
	{
	deck[card].rank = rank;
		//deck[card].rank = static_cast<CardRank>(rank);
		++card;
	}

	return 0;
}


error reported:
..\src\main.cpp:17:13: error: request for member 'rank' in 'deck.std::array<_Tp, _Nm>::operator[]<int, 52ull>(((std::array<int, 52ull>::size_type)card))', which is of non-class type 'std::array<int, 52ull>::value_type {aka int}'
In my code below, can I use .member functions for std::array?

Certainly. But the elements of the array-of-int you have here don't have a rank member.
How do I assign a rank member to array-of-ints elements? Just learning std::array.
You don't.

If you want an array of elements that have a 'rank' member, you must define that type first. Then, you may make an array of elements of that type.
you must define that type first. Then, you may make an array of elements of that type.


Hate to ask this, but can you please post an example snippet? If u have time.
Last edited on
I assume something like this:
1
2
3
4
5
6
7
8
9
struct Card {
    int rank;
    // ...
};

// ...

std::array<Card, 52> deck;
deck[0].rank = 0;
Seeing both the "old way" and the c++11 std::array in one context helped me understand this better. Both take objects of a certain type and members. I was used to using an array of structs before c++11...and then it was lost on me with std::array--> but its a lot clearer now.

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

using namespace std;

struct Card {
    int rank;
};

int main()
{

std::array<Card, 52> deck;
deck[0].rank = 99;
cout<<deck[0].rank<<endl;

//older way

Card * n_ptr = new Card();
n_ptr->rank = 1020;
cout<<n_ptr->rank;
return 0;

}

Last edited on
Note that the members of Card/deck remain uninitialized unless you provide a constructor.
Do I provide that constructor by initializing the object Card card?
Study classes so you'll get a good grip on all of this stuff - http://www.cplusplus.com/doc/tutorial/classes/
Thx
Topic archived. No new replies allowed.