2

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

0

2 Answers 2

3

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

I think you are absolutely right, strict weak ordering (<) is required condition for the key which is not possible in char[].
@AgrudgeAmicus That part isn't a big problem. You could provide a comparator solving that: template<typename T> struct less { using type = typename std::remove_extent_t<T>; static constexpr size_t extent = std::extent_v<T>; constexpr bool operator()(const type (&a)[extent], const type (&b)[extent]) const { return std::lexicographical_compare(std::begin(a), std::end(a), std::begin(b), std::end(b)); } };
0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.