Kriso Kriso - 1 year ago 59
C++ Question

What is a good way to store color?

I started to make "game of life" and I thought, what if I could have more states than 1 or 0.

But then I need different colors. I want the colors to be linked to a grid/object (the grid is a class).

What is a good/decent way to store color pallets for fast/easy access?

My current less than ideal solution was to have 4 pointers to memory for each red, green, blue and alpha value.

In my class I had a function to set the color of value

to rgba:

SetColor(v, r, g, b, a) //Set v to the appropriate color values

I would like to keep this function to easily modify a color.

Answer Source

What I use is something really simple: 4 floats

struct Color {
    float r, g, b, a;

Then, you can have something like a color pallete:

// a Palette of 8 colors:
using palette_t = std::array<Color, 8>

palette_t myPalette { /* ... */ };

Then, in your grid or object class, you can reference the color with an index:

struct Grid {
    // lot's of code

    std::size_t colorIndex = 0;

But then you asked how to have easy access to the color (I guess the easy access is from within the Grid class)

There is a lot of solution that can exists, and most will depend of your project structure. This is one idea many others. I hope it will inspire you.

You can store a function that return the right color:

struct Grid {
    // lot's of code

    std::size_t colorIndex = 0;
    std::function<Color(std::size_t)> color;

And then, have something that create your grid correctly:

struct GridCreator {
    GridCreator(const palette_t& aPalette) : palette{aPalette} {}

    Grid create(std::size_t color) const {
        Grid grid;

        // create the grid

        grid.color = [this](std::size_t index) {
            return palette[index];

        return grid;

    const palette_t& palette;

Then you got free access to your color palette without directly knowing that the palette exists from the Grid class.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download