intmain() { std::map<std::string, int> student = { {"Xiao Ming", 10}, {"Xiao Hua", 15}, {"Xiao hong", 13} }; std::string name; try { name = "Xiao Ming"; auto age = student.at(name); std::cout << name << "'s age is " << age << std::endl;
name = "Xiao Lan"; age = student.at(name); std::cout << name << "'s age is " << age << std::endl; } catch (const std::out_of_range& e) { std::cerr << e.what() << '\n' << name << "was not found.\n"; }
return0; }
// ---------------------- // output // Xiao Ming's age is 10 // invalid map<K, T> key // Xiao Lanwas not found. // ----------------------
在上面的实例中,当获取 Xiao Lan 的 age 时,由于键值中不存在 Xiao Lan,因此 at() 抛出 invalid map<K, T> key 异常。