Question about 2D Array

Hey guys, I have a question.



Please reference this YouTube video. Skip to 2:46 minute.

https://youtu.be/Hq4NXKg84gM

You will see that there is a function called CreateMap which has a loop that prints the map array by cout << map[i]. Though I thought to print out a 2D array it should be cout << map[i][j].

How in his video did he print out the whole 2D array map by only printing the array as 1D?
Last edited on
I did not watch the video, but it is always possible to overload an insertion operator for this kind of thing. (It is not always advisable, though.)

If the map is a vector of vector, then the insertion operator is easy:

1
2
3
4
5
6
7
template <typename T>
std::ostream& operator << ( std::ostream& outs, const std::vector <T> xs )
{
  for (auto x : xs)
    outs << x << " ";
  return outs;
}

You could have even output the entire map that way with an additional insertion operator:

1
2
3
4
5
6
7
template <typename T>
std::ostream& operator << ( std::ostream& outs, const std::vector <std::vector <T> > & xs )
{
  for (auto x : xs)
    outs << x << "\n";
  return outs;
}

Then you could simply cout << map;

Hope this helps.
In an expression like cout << "Hello\n", the type of the string literal "Hello\n", is char const[7]. cout makes the assumption that this array of (const) char represents a C-string, and puts the whole string into the stream.

In this particular case, the object map has the type char[X][Y]. The element type of the array (the type of map[i]) is char[X].

Give an array of char to cout, and it is treated like a C-string. The whole string is put into the stream.

Topic archived. No new replies allowed.