Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing an array of sets of coordinates in C++ (vector of vector of pairs?)

First of all, I am very new to C++ so I may have to dip into pseudocode and/or Python to explain what I'm trying to do...

I'm trying to store pairs of X and Y coordinates for each frame of an animation, for multiple sprites. I envisaged this to be something like the following - assume that PLAIN == 1 (using an enum):

animationFrames[PLAIN][0] = { 20, 50 }
animationFrames[PLAIN][1] = { 25, 55 }

Et cetera. I essentially would like to be able to query animationFrames with the ID of the sprite in question and receive a set of X,Y coordinates to iterate over. I'm finding this quite tricky. Here's my attempt, which does not work...

std::vector< std::vector< std::pair<int, int> > > frames = {
    {
        { 1, 1 }, { 2, 2 }  // two frames for sprite A
    },
    {
        { 3, 3 }, { 4, 4 }  // two frames for sprite B
    }
};

This results in the following error message:

prog.cpp: In function 'int main()':
prog.cpp:15: error: braces around initializer for non-aggregate type 'std::vector<std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > >, std::allocator<std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > > > >'

I've tried various mutations of vectors, pairs, and arrays, but I can't seem to figure it out.

Thanks in advance!

like image 328
Benwithjamin91 Avatar asked Oct 19 '22 06:10

Benwithjamin91


1 Answers

I think your compiler is perhaps not able to handle the C++11 standard, meaning that it doesn't support brace initialisation. You can just add the items one by one:

std::vector<std::vector<std::pair<int, int> > > frames(2);
std::vector<std::pair<int, int> > &v1 = frames[0];
v1.push_back(std::pair<int, int>(1, 1));
v1.push_back(std::pair<int, int>(2, 2));
std::vector<std::pair<int, int> > &v2 = frames[1];
v2.push_back(std::pair<int, int>(3, 3));
v2.push_back(std::pair<int, int>(4, 4));

It's a lot uglier, but it should work. If on the other hand your compiler does support C++11, you shouldn't even need the =, and you can remove some whitespace:

std::vector<std::vector<std::pair<int, int>>> frames {
    {
        { 1, 1 }, { 2, 2 }  // two frames for sprite A
    },
    {
        { 3, 3 }, { 4, 4 }  // two frames for sprite B
    }
};

Note that some older compilers may require a command-line argument to enable C++11 support. For example, older versions of GCC (g++) require -std=c++11.

like image 145
davmac Avatar answered Oct 21 '22 06:10

davmac