PEIN
PEIN

Reputation: 308

Char 2D array in map in C++

How can I use a 2D char array with a map in C++. I want to do this:

map<char[50][50],int>M;

char brr[50][50];
//some operation here on the array
int aa=1;

if(M.find(brr)==M.end())
{
     M[brr]=aa;
     aa+=1;
}

what am I doing wrong?

EDIT:

I've just found another way. This way I can achieve what I stated in my question. Instead of using the 2d array I'm just gonna convert it into a string and use it. It'll still yield the same result:

map<string,int>M;

char brr[50][50];
//some operation here on the array
int aa=1,i,j;

string ss="";

for(i=0;i<50;i++)
{
     for(j=0;j<50;j++)
     {
         ss+=brr[i][j];
     }
}

if(M.find(ss)==M.end())
{
     M[ss]=aa;
     aa+=1;
}

Upvotes: 0

Views: 1737

Answers (2)

Node
Node

Reputation: 3509

You have to use a wrapper class, and it needs to support operator<. If a lexographical ordering is fine, you can do something like this:

#include <boost/array.hpp>
#include <map>

int main()
{
    typedef boost::array<boost::array<char, 50>, 50> Array;

    std::map<Array, int> m;
}

boost::array can be replaced with std::array if you are using C++11.

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272467

You can't. Arrays can't be assigned to (i.e. you can't do brr = XXX; in your example), and this is a requirement of the key type of a std::map. Also, the key needs to have a strict weak ordering defined on it (i.e. it needs operator< or a comparator function).

You could consider wrapping your array in a class, defining an appropriate operator <, and then using this as the key type.

Upvotes: 4

Related Questions