【问题标题】:Auto declaration of map iterator error on GCC在 GCC 上自动声明映射迭代器错误
【发布时间】:2016-12-07 09:16:18
【问题描述】:

我的地图定义为:

std::map<unsigned int, std::string> spCalls;  

我还有一个函数可以返回字符串,给定键。定义为:

std::string spGetCallString(unsigned int key)
{
    auto iter{ spCalls.find(key) };

    return iter->second;
}

当尝试使用 GCC 编译它时,我收到一个错误提示

error: base operand of '->' has non-pointer type
'std::initializer_list < std::_Rb_tree_iterator < std::pair < const unsigned int, std::basic_string < char> > > >'

 return iter->second;"

我无法理解这一点,我不明白为什么我的代码不应该工作。感谢您的帮助。

【问题讨论】:

标签: c++ c++11 gcc auto c++17


【解决方案1】:

在 C++17 之前,花括号初始化器的 auto type deduction 将始终产生 std::initializer_list 的实例化类型,因此对于 auto iter{ spCalls.find(key) };iter 的类型将是 std::initializer_list&lt;std::map&lt;unsigned int, std::string&gt;::iterator&gt;,这与完全使用。

从 C++17 开始,您将获得正确的类型,即std::map&lt;unsigned int, std::string&gt;::iterator

在直接列表初始化中(但不在复制列表初始化中), 当从一个花括号初始化列表中推断出auto 的含义时, braced-init-list 必须只包含一个元素,并且 auto 的类型 将是该元素的类型:

auto x1 = {3}; // x1 is std::initializer_list<int>
auto x2{1, 2}; // error: not a single element
auto x3{3};    // x3 is int (before C++17 it was std::initializer_list<int>)

如果您的编译器仍然不支持,您可以将大括号初始化器更改为其他初始化器,例如

auto iter = spCalls.find(key);
auto iter(spCalls.find(key));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-15
    • 2011-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多