1

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.

  • run under a debugger or through *valgrind* – bruno Apr 22 '20 at 15:15
  • We can't reproduce your error and help you if you don't give us a [Minimal and Reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Aplet123 Apr 22 '20 at 15:18
  • what reference do you expect to get in *a* ? does `find` return `end` in your case ? – bruno Apr 22 '20 at 15:19
  • [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173/5910058) – Jesper Juhl Apr 22 '20 at 15:19
  • 3
    ***It compiles fine*** contradicts the title of your question. Note that the job of the compiler is 100% complete when it finishes the compilation of your code. Your title probably should be adjusted to note that the execution of your program terminates unexpectedly or similar. – drescherjm Apr 22 '20 at 15:42

2 Answers2

6

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

bruno
  • 32,421
  • 7
  • 25
  • 37
2

If multimap does not have an item with key 0, then multimap.find(0) returns an iterator that is not dereferenceable. Always check the return values of such calls before dereferencing the iterator.

auto iter = multimap.find(0);
if ( iter != multimap.end() )
{
   std::multimap<short,short> &a = iter->second;
   std::pair<short,short> z={1,2};
   a.insert(z);
}
else
{
   // Decide what to do
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270