c++ - 为什么我不能写container.iterator?

标签 c++ syntax

为什么我不能这样写代码:

int main()
{
    std::map<std::string, int> m;

    m.iterator it = m.find("five");
    //~~~^~~~~
    // nor like this:
    m::iterator it = m.find("eight");
}

最佳答案

您无法编写m.iterator,因为iterator不是数据成员或成员函数,因此无法对其使用成员访问运算符(即operator.)。 (iterator是一个嵌套的类型名称。)
您无法编写m::iterator,因为m不是类名或 namespace 名称,因此不能与范围运算符(即operator::)一起使用。
您可以使用auto(从C++ 11开始)来推导类型。

auto it = m.find("five"); // the type would be std::map<std::string, int>::iterator 
或通过decltype获取类型(从C++ 11开始)。
decltype(m.begin()) it = m.find("five");   // the type would be std::map<std::string, int>::iterator 
decltype(m)::iterator it = m.find("five"); // same as above

关于c++ - 为什么我不能写container.iterator?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63032743/

相关文章:

c++ - 我如何在 CUDA 中正确使用全局内存?

java - 使用 Java Nashorn 引擎仅验证 javascript

haskell - 为什么我做不到 (flip (+).digitToInt) $ '4' 4

javascript - 是否可以用 meteor 中的变量替换 .find() 查询?

python - 从 OpenGL 深度缓冲区获取世界坐标

c++ - 这种重载 operator new 有什么问题吗?

c++ - 为什么我调用 'wxGetTranslation' 会导致编译器错误 "ambiguous call to overloaded function"?

c++ - .o 生成具有不同规则的 Makefile

objective-c - 如何访问某些方法的 Objective C 未命名参数?

Swift 3 名称(大写与否)?