0

This will be my 1st question here. I have came across an issue that I would like to resolve in a program that I'm working on (doing some intern/developer shadowing tasks).

I have a std::map data structure. Every time I pass from the cmd line a value that is not mapped I get the: terminate called after throwing an instance of 'std::out_of_range' what(): map::at Aborted (core dumped)

And it is fine, this is the way it should be. However what I would like to achieve is to validate the user input and if the value is not present in the map then for example capture the above event in a variable and then print it out.

Every conditional statement that I try is not working as I would like to as it instantly throws out that "terminate called..." ad closes down the whole program.

FrankH
  • 25
  • 5
  • 1
    Please show a [mcve], don't just describe the issue – UnholySheep Aug 11 '21 at 09:05
  • Is getting input and checking if the key is already in the map an ok solution? https://stackoverflow.com/questions/1939953/how-to-find-if-a-given-key-exists-in-a-c-stdmap – GustavD Aug 11 '21 at 09:05
  • Sorry but as mentioned. Tried to do it with if statements and it was not working and only throwing that terminate called. – FrankH Aug 11 '21 at 10:46

2 Answers2

0

you should surround your std::map::at(key) call inside a try/catch block as in

std::map<std::string, int> my_map = {{"one",1}, {"two":2}};

try
 { 
  auto val = my_map.at("three");
  std::cout << "my value at 'three' is " << val << "\n"; 
 } 
catch(std::out_of_range const & e)
 { 
  std::cerr << "oops 'three' is not in your map\n";
 }
kenny
  • 256
  • 1
  • 5
  • 15
0

You can catch the error with a try-catch block but you can easily avoid throwing it in the first place.

In c++20 you can use std::map.contains(key_type) to check whether it is in the map.

Without c++20 you can use std::map.find(key_type) and then assert that it is not equal to std::map.end().

Example:

std::map<int,int> a = {{1, 5}, {2, 3}};
if(a.contains(3))
    // Do something
else
    // Do something else

auto it = a.find(2)
if(it != a.end()) // Meaning that value was found
    // Do something
else
    // Do something else 
Lala5th
  • 1,137
  • 7
  • 18