Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating a class that can receive board1[{1,1}]='X'; ? (curly brackets inside square brackets)

I got H.W. that in one of the lines of the main.cpp I am suppose to support:

board1[{1,1}]='X';

the logical meaning behind this is to assign to a "game board" the char 'X' at the position of (1,1). I have no clue how to create an array that receives curly brackets such as [{int,int}].

How can I do this?

P.S. since these are symbols and not chars (and since I don't recognize any term that belongs to this problem) it is very difficult searching for this type of problem in google, so this might be a duplicate :-( , hope not.

I tried to do:

first try:

vector<vector<int> > matrix(50);
for ( int i = 0 ; i < matrix.size() ; i++ )
    matrix[i].resize(50);
matrix[{1,1}]=1;

2nd try:

int mat[3][3];
//maybe map
mat[{1,1}]=1;

3rd try:

class _mat { // singleton
    protected:
       int i ,j;

    public:
        void operator [](string s)
        {
            cout << s;
        }
};

_mat mat;
string s = "[{}]";
mat[s]; //this does allow me to do assignment also the parsing of the string is a hustle
like image 446
Tomer Avatar asked Jan 03 '23 11:01

Tomer


2 Answers

you need to do something like:

    struct coord {
        int x;
        int y;
    };

    class whatever
    {
        public:
            //data being what you have in your board
            data& operator[] (struct coord) {
                //some code
            }
    };
like image 83
Tyker Avatar answered Jan 04 '23 23:01

Tyker


Your first attempt, was pretty close to working actually. The issue is that the [] operator for the vector takes an integer index into where in the vector you want to change (and the vector must be large enough for it to exist). What you wanted however is a map; which will create the item and assign it for you. Thus a std::map<std::vector<int>, char> would've got you what you wanted. (although it might not have the best performance).

Your second attempted failed for the same reason as the first (index needs to be an integer) and the 3rd is corrected by the answer by Tyker.

like image 45
UKMonkey Avatar answered Jan 05 '23 01:01

UKMonkey