Search code examples
c++structmultimap

Inserting a struct as a value in Multimap and Iterating the same to get the values


#include <stdio.h>
#include <map>
struct temp
{
   int x;
   int id;
};

int main()
{
    temp t;
    int key;
    typedef std::multimap<int,struct temp> mapobj;
    t.x = 10;
    t.id = 20;
    key=1;
    mapobj.insert(pair<int,struct>key,t);
    //mapobj.insert(1,t);
    
    return 0;
 }

I am new to STL multimap, I'm trying to insert my structure data inside the multimap but I get this error:

main.cpp:25:11: error: expected unqualified-id before ‘.’ token
     mapobj.insert(pair<int,struct temp>key,t);
           ^

seeking your suggestion on this.


Solution

  • I think you need to make some minor code changes to fix the compile error as follows:

    1. Add 2 brackets: mapobj.insert(std::pair<int,struct temp> (key,t) );
    2. Add "struct temp" in mapobj.insert(std::pair<int,struct temp>(key,t)); (Note: You did not have the name of the struct: temp).
    3. Please note that you should specify std::pair the second times you use mapobj at the bottom of your file.
    4. Remove the keyword Tydef (as user "Sam Varshavchik" mentioned because you don't need to define a new type and you only need to define a new variable).
    5. BTW, the following issue does not cause the compile error, but it will be a good thing if you initialize the value of "key" because if you do not initialize the value for "key", then key may have random values that is not zero. This is called undefined behavior, and it may cause some bug later on.

    Here is the new code that compiles successfully:

    #include <stdio.h>
    #include <map>
        
    struct temp
    {
       int x;
       int id;
    };
    
    int main()
    {
        temp t;
        int key = 1; // You should initialize the key
        std::multimap<int,struct temp> mapobj; // I fixed this line
        t.x = 10;
        t.id = 20;
        key=1;
        mapobj.insert(std::pair<int,struct temp>(key,t)); // I fixed this line
        //mapobj.insert(1,t);
        
        return 0;
     }