Search code examples
c++multimap

compiler doesn't finish process


I have a multimap which key is short and value is the other multimap

std::multimap<short,std::multimap<short,short>> multimap

now I want to do it`

std::multimap<short,short> &a=multimap.find(0)->second;
std::pair<short,short> z={1,2};
a.insert(z);

It compiles fine. But when I run it it just stops and doesn't finish the process, It even doesn't throw any runtimeerror. Have any ideas? Thanks in advice.


Solution

  • Having

    std::multimap<short,std::multimap<short,short>> multimap
    ...
    std::multimap<short,short> &a=multimap.find(0)->second;
    std::pair<short,short> z={1,2};
    a.insert(z);
    

    If find returns multimap::end that one shall not be dereferenced, but you do and get a reference to second, the behavior is undefined when later to use that reference to insert.

    So of course check if find succes, like

      std::multimap<short,std::multimap<short,short>> multimap;
      std::multimap<short,std::multimap<short,short>>::iterator it = multimap.find(0);
    
      if (it == multimap.end()) {
        ...
      }
      else {
        std::multimap<short,short> &a = it->second;
    
        std::pair<short,short> z={1,2};
        a.insert(z);
      }
    

    Out of that your title "compiler doesn't finish process" is not very clear, the execution is not the one you expect, but the compiler does not run the process