Reputation: 1103
I am trying to use char[]
as a key for a map
:
#include<iostream>
#include<map>
#include<string>
#include<utility>
#include<list>
using namespace std;
int main(void)
{
map<char[10],int> m;
char c[10]={'1','2','3','4','5','6','7','8','9','0'};
m[c]=78;
return 0;
}
But is throwing an error:
error: array used as initializer
second(std::forward<_Args2>(std::get<_Indexes2>(__tuple2))...)
even this doesn't work: m["abcdefghi"]=4;
How to use char []
as a key? I have couple of questions on SO but they didn't help much.
NOTE: I have used string
but I want to try char[]
just for curiosity
Upvotes: 2
Views: 1187
Reputation: 29985
Use std::array
:
#include <array>
#include <iostream>
#include <map>
int
main()
{
using key_type = std::array<char, 10>;
std::map<key_type, int> m;
key_type c{ '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' };
m[c] = 78;
}
If you want variable size, use std::string_view
:
#include <iostream>
#include <map>
#include <string_view>
int
main()
{
std::map<std::string_view, int> m;
char c[10] = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' };
m[{c, sizeof(c)}] = 78;
}
Upvotes: 0
Reputation: 310990
Arrays have neither the copy constructor nor the copy assignment operator. And there is no default operator < for arrays.
Instead of array use the standard container std::array
.
For example
#include<iostream>
#include <array>
#include<map>
int main()
{
std::map< std::array<char, 10>, int> m;
std::array<char, 10> c = {'1','2','3','4','5','6','7','8','9','0'};
m[c]=78;
return 0;
}
Upvotes: 3