小编R S*_*ath的帖子

什么时候应该使用const_iterator而不是auto

下面是一个例子,我想说明最好使用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)

c++ c++11

6
推荐指数
1
解决办法
372
查看次数

标签 统计

c++ ×1

c++11 ×1