Search code examples
c++dictionarystlinsertion

STL Map: What does this command mean?


I've come across a solution of a competition problem that uses the STL Map, with a different kind of insertion that I've already known. I know these kind of insertions (and their differences):

Map[key] = value; and Map.insert(make_pair(key,val));

But this one I've no idea what it's doing, just that it works for the problem that I need to solve:

   std::map<int, int> freq;
   int inp;
   // ...

   for (int i = 0; i < n; i++)
    {
        scanf ("%d", &inp);
        freq [inp]++;
    }

    for (int i = 0; i < m; i++)
    {
        scanf ("%d", &inp);
        freq [inp]--;
    }

Where freq is a map with a pair of ints, and inp is a normal integer.


Solution

  • could you show where you initialized freq?, if freq is a "pair" of ints you need to access them with "freq[inp].first" and "freq[inp].second" and as far as i know "pair" don't have the + or - operator overloaded.

    for (int i = 0; i < n; i++)
    {
        scanf ("%d", &inp);
        freq [inp]++;
    }
    

    here, freq is storing how many times an integer was found on the input, if the input is: 0, 0, 0, 1,1

    map[0] = 3, and map[1] = 2

    for (int i = 0; i < m; i++)
    {
        scanf ("%d", &inp);
        freq [inp]--;
    }
    

    the same, just subtracting.

    in this case, you can't:

    Map.insert(make_pair(key,val));
    

    becouse with:

    std::map<int, int> freq;
    

    you're saying that your map will have an integer as a "key" and an intenger as a "value", is no't a "map of pairs" is just a map, would have been a map of pairs if you had initialized as std::map > freq;

    Map[Key] = Value;
    

    if this is a competition problem, i recommend you to just use an array, set it size to the biggest you will need, and initialize it in 0 as required.