Home > Net >  What is the max input size of an index in a map?
What is the max input size of an index in a map?

Time:10-29

I want to store a number 108 as an index in a map. Is it possible? If yes, what is the max value of the index we can use in a map?

CodePudding user response:

std::map stores entries looked up by keys, not by indexes. It is not an array.

The maximum value you can use for a key is determined by whatever data type you decide to use for the key. For instance, 108 will easily fit in a std::(u)int32_t (or larger) integer type, which has a max value of 2147483647 (signed, 231-1) or 4294967295 (unsigned, 232-1). You can use std::numeric_limits::max() to determine the max value of any numeric type.

The std::map::max_size() method returns the maximum number of entries (ie, unique keys) that can be stored in the map, regardless of their values. For instance, if you stored key 0 and key 100000000 (108), there would only be 2 keys in the map, not 100000001 keys.

Unlike an indexed array, the values of the keys for a std::map matter only for uniqueness, not for count.

CodePudding user response:

I will write it as an answer, since comment does not have fine code formatting.

#include <iostream>
#include <string>
#include <map>

using namespace std;

int main()
{
    map<string, string> my_map;
    int whatever_number = 100000000;

    string key = to_string(whatever_number);

    my_map[key] = "Hello World!\n";

    cout << my_map[key];
}
  • Related