user1529540
user1529540

Reputation:

Is it possible for the Keys of a map to be arrays? (Map array error)

I want to make a map which has arrays of the form int[27] as Keys, So I tried the following:

#include <map>
using namespace std;
map<int[27] ,int> mapa;
int n[27];
int main(){
    mapa[n]++;
}

But I get an error, is it because arrays can't be used as key type for a map?
What can I do in this case? Would it work if I used a vector instead of an array?


Is this the suggestion?

#include <cstdio>
#include <map>
using namespace std;
map<array<int,27> ,int> mapa;
int n[27];
int main(){
    mapa[n]++;
}

This is the version that works:

#include <cstdio>
#include <map>
#include <array>
using namespace std;
map<array<int,27>, int> mapa;
array<int,27> v;
int main(){
    mapa[v]++;
    printf("%d\n",mapa[v]);
}

Upvotes: 1

Views: 66

Answers (2)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

But I get an error, is it because arrays can't be a map?

I think you actually mean map key type. No, raw arrays can't be used as keys, because there's no intrinsic less operator declared for them.

What can I do in this case? Would it work if I used a vector instead of an array?

Yes, you can use std::vector<int> as key. Even better yet std::array<int,27>, if you know it's a fixed size of 27.

The exact documentation how std::less() works with std::array can be found here.

Alternatively you can provide your own comparison algorithm as @NathanOliver was pointing out.


Is this the suggestion?

#include <cstdio>
#include <map>
using namespace std;
map<array<int,27> ,int> mapa;
int n[27];
int main(){
    mapa[n]++;
}

Almost. You need

std::array<int,27> n;

there of course, there's no automatic conversion.

Upvotes: 2

MtCS
MtCS

Reputation: 305

This would compile:

map<int *,int> mapa

But it is not what you want... Arrays are almost the same as pointers, therefore you cannot build a map of arrays. It would only compare the pointer in memory when retrieving/setting its value, not its content.

Upvotes: 0

Related Questions