How do I create a List within a multi-dimensional array / grid c++

时间:2018-12-03 13:19:08

标签: c++ arrays list multidimensional-array grid-search

I have reached a stumbling block in my program. I am programming in c++ and using OpenGL for graphics. I am looking to partition the space with a grid (represented with a 2D array - grid[rows][cols]). The grid will have 'cells' at each index.

Within this grid and at each INDEX location i.e. grid[0][0] I want a list of object ID's (int values) to be collected as they move into each grid cell. The list at index location grid[0][0] should be updating in real-time / dynamically with moving objects on the screen.

I want to retrieve the object ID's as they populate the list for collision checking later.

As a visual it should be as follows:

Grid Array

+[0][0] --> List[]

+[0][1] --> List[]

+[0][2] --> List[]

+[0][3] --> List[]

+[1][0] --> List[]

+[1][1] --> List[] ...and so on

Is there a way to do this in C++? Java seems to be able to create new arrays within array spots as I need...there must be a way?

Hash tables, linked lists are so far over my head...but if they are what I need to know then please let me know and I will look into them in more detail... Many thanks in advance.

1 个答案:

答案 0 :(得分:0)

尝试这样:

const contexts = [
    { channel: 'email', preset: 'christmas', field: 'preamble bottom' },
    { channel: 'web', preset: 'christmas', field: 'preamble bottom' },
    { channel: 'email', preset: 'deal', field: 'preamble top' },
    { channel: 'email', preset: 'sale', field: 'preamble top' },
    { channel: 'web', preset: 'deal', field: 'preamble top' },
    { channel: 'web', preset: 'sale', field: 'preamble top' }
];

const contexts2 = [
    { channel: 'email', preset: 'deal', field: 'vignette' },
    { channel: 'email', preset: 'deal', field: 'headline' },
    { channel: 'web', preset: 'deal', field: 'vignette' },
    { channel: 'web', preset: 'deal', field: 'headline' }
];

const group = (arr) => {

    const byField = new Set(arr.map(({ field }) => field));

    const byPreset = Array.from(byField).reduce((acc, val) => {

        const keys = new Set(arr.map(({ field, preset }) => field === val ? preset : null)
                                .filter((item) => item));

        const key = Array.from(keys).join(',');

        acc[key] = acc[key] ? `${acc[key]},${val}` : val;

        return acc;

    }, {});

    return Object.keys(byPreset).reduce((acc, val) => {

        const fields = val.split(',');

        const keys = new Set(arr.filter(({ channel, preset }) => fields.some((item) => item === preset))
                                .map(({ channel }) => channel));

        const key = Array.from(keys).join(',');

        acc[key] = { ...acc[key], [val]: byPreset[val] };

        return acc;

    }, {});
};

console.log(group(contexts));

console.log(group(contexts2));