Springfox
Springfox

Reputation: 1419

C++ returning an array of objects from a class method

I am trying to return a two dimensional array of 'room' objects as a kind of print/display of what's in the array.

Room* m_map[10][10];

generated like so:

//Initialise array to NULL
for(int x=0;x<10;x++)
{
    for(int y=0;y<10;y++)
        m_map[x][y] = NULL;
}

for(int n=0; n<10; n++)
{       
    for(int ran=0; ran<3; ran++)
    {
        int r_n = rand() % 10 ;

        Room* r = new Room(n, "Normal", true, false, false, true);
        m_map[r_n][n] = r;
    }       

}

So what this gives is a scatter of Rooms in the array.

I'd then like to display/print for the user where these rooms are, in reference to the NULL.

So I could for example if NULL display '#', if it's a Room Leave a ' '.

I'm unsure of the bit I should return in the method.

Any help or pointing in the right direction would really be appreciated

Upvotes: 1

Views: 2455

Answers (2)

juanchopanza
juanchopanza

Reputation: 227390

It would be easier to use an std::array<Room, N> if the array is fixed size (and the size is known at compile time), or an std::vector<Room> if it isn't.

#include <array> // or <tr1/array> if no C++11

std::array<Room, TheSize> returnArray() const
{
    return m_map;
} 

Be careful though, depending on the use-case, you might want to return a reference, not a copy:

const std::array<Room, TheSize>& returnArray() const
{
    return m_map;
} 

That said, if all you want to do is print some objects, then don't expose implementation details such as the array. You can either provide a print function ot, better still, override std::ostream& operator<< for your type.

// inside your class declaration:
friend 
std::ostream& operator<<(std::ostream& o, const MyClassWithRooms& r)
{
  // loop over r.m_map and print to o
}

Edit If the array is 2D (as mentioned in comments) then there are options: a nested array structure (std::array<std::array<T,N>,M>, or a "flat" N*M array, and some careful playing with indices).

Edit 2: If you need to store things that can be either set or not, you could use arrays or vectors of std::unique_ptr<Room> instead of plain old Rooms of raw Room*. Another option is simply to use a 2D map, an std::map<int, std::map<int, Room>>.

Upvotes: 7

default
default

Reputation: 2757

Easiest way to do it is to use a std::vector< Room > for your array. That way you don't have to worry about memory management, and the size is built into the array.

Upvotes: 0

Related Questions