下面是一个例子,我想说明最好使用const_iterator来"const auto".这是因为容器不提供cfind()函数.还有其他选择吗?或者应该使用"const auto"并忽略const的缺失?
std::string GetJobTitle(const std::string& employee)
{
using EmployeeTitles = std::unordered_map<std::string, std::string>;
EmployeeTitles employees = { { "Alice", "Director" },{ "Bob","Manager" } ,{ "Charlie", "Developer" } };
// Option 1. const_iterator is access only:
EmployeeTitles::const_iterator itr = employees.(employee);
if (itr != employees.cend())
{
itr->second = "Project Manager"; // error C2678: The compiler prevents us changing the job tile which is what we want
return itr->second;
}
// Option 2. const auto is more concise but is not as safe: …Run Code Online (Sandbox Code Playgroud)