Tell me, please, how to create a map correctly.

  • map <char [2], long long>. - Arthur
  • How do you want to compare keys? - Vlad from Moscow
  • In the sense of? Like regular strings. According to the first letter, if equal, then according to the second. - Arthur
  • If you want to compare only one character, then why not declare map <char, long long>? - Vlad from Moscow
  • Two. Two characters. - Arthur

1 answer 1

For example, you can declare as follows

auto cmp = [](const char *a, const char *b) { return ::strcmp(a, b) < 0; }; std::map<char[2], long long, decltype(cmp)> m(cmp); 

However, since arrays do not have an assignment operator, it is better to declare the key as having the type std::array<char, 2> .

For example,

 #include <iostream> #include <map> #include <array> int main() { auto cmp = [](const std::array<char, 2> &a, const std::array<char,2> &b ) { return ::strcmp(a.data(), b.data()) < 0; }; std::map<std::array<char, 2>, long long, decltype(cmp)> m(cmp); m.insert({ { { "A" }, 'A' }, { { "B" }, 'B' }, { { "C" }, 'C' } }); for (const auto &p : m) { std::cout << p.first.data() << ": " << p.second << std::endl; } } 

The output of the program to the console:

 A: 65 B: 66 C: 67 

If map contains as keys a string containing two characters besides the terminating zero, then you need to declare the key as std::array<char, 3>

You can simplify the code if you use the std::string type as the key, not a character array.

Then you can write just

 std::map<std::string, long long> m; 
  • Thank you very much. - Arthur
  • @Arthur Not at all. The conclusion from my answer is that you should use the map <std :: string, long long> - Vlad from Moscow