1

I am trying write a function that reads PPM images and the function should return the contents.

PPM images have the following text format:

P3
numOfRows numOfColumns
maxColor
numOfRows-by-numOfColumns of RGB colors

Since the text format has a mixture of variable types, is there any way to store this all in an array? I remembered that C++ does not support arrays with different types. If not, then I am thinking of defining a class to store the PPM contents.

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
roulette01
  • 1,984
  • 2
  • 13
  • 26
  • What do you mean by *"it will have a mixture of types"*? It won't. If the header is P3 it will all be ASCII, if the header is P6, it will be binary. And it will all be integers. – Mark Setchell Mar 11 '16 at 22:47

2 Answers2

1

C++ does not support arrays with different types.

Correct.


You could:

  1. Define a class as you say, like this: C++ Push Multiple Types onto Vector or this: Creating a vector that holds two different data types or classes or even this: Vector that can have 3 different data types C++.
  2. Have a generic C-like array (or better yet, an std::vector) with void*.
Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305
0

C++ isn't Javascript. The number of columns / number of rows must be integers. Maximum colour value might be either an integer or a float depending on the format details, as might the rgb values.

So you read the image dimensions first. Then you create a buffer to hold the image. Usually 32 bit rgba is what you want, so either allocate width * height * 4 with malloc() or use an std::vector and resize. Then you loop through the data, reading the values and putting them into the array. Then you create an "Image" object, with integer members of width and height, and a pixel buffer of 32 bit rgbas (or whatever is your preferred pixel format).

Malcolm McLean
  • 6,258
  • 1
  • 17
  • 18