为什么我不能这样写代码:
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/