声明 std::map 迭代器会导致一个奇怪的错误
Declaring a std::map iterator causes a weird error
我只是想声明一个映射迭代器,但我收到一个编译错误,说"预期;在它之前"
我相信这是因为我没有包含整个 std 命名空间(使用命名空间 std;)但我故意不想包括所有这些。
我的代码:
#include <map>
#include <string>
template <class Object>
class Cont
{
public:
Cont() {}
Object* get( unsigned int nID )
{
std::map <unsigned int, Object*>::iterator it = m.begin(); // error here "expected ; before it" what is this error?
for ( ; it != m.end(); it++ )
{
if ( (*it).second->ID == nID ) { return (*it).second; }
}
return NULL;
}
std::map <unsigned int, Object*> m;
};
我也试过这个,但它不起作用:
std::map <unsigned int, Object*>::std::iterator it = m.begin();
如果我
没记错,因为您使用的是模板参数,则需要在迭代器声明前面加上 typename
.
typename std::map <unsigned int, Object*>::iterator it = m.begin();
你的编译器和标志设置是什么? 我能够构建这个OK。
// test.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <map>
#include <string>
class Foo
{
public:
int ID;
};
template <class Object> class Cont
{
public:
Cont() {}
Object* get( unsigned int nID )
{
std::map <unsigned int, Object*>::iterator it = m.begin(); // error here "expected ; before it" what is this error?
for ( ; it != m.end(); it++ )
{
if ( (*it).second->ID == nID ) { return (*it).second; }
}
return NULL;
}
std::map <unsigned int, Object*> m;
};
int _tmain(int argc, _TCHAR* argv[])
{
Cont<Foo> c;
c.get( 2 );
return 0;
}
你没有说你正在使用什么编译器,但只需将其剪切并粘贴到一个新文件中,它在VS2010中就可以很好地编译。你不需要using namespace std;
肯定....
(还有你放另一个std的皱纹::在迭代器有创意之前,但不正确。您指定地图类模板位于命名空间 std:: 中,迭代器是嵌套在地图模板中的类型。
相关文章:
- 试图修复一个错误,该错误不会让我开始编程其余部分
- MSVC 无法根据模板参数进行数学运算,这是一个错误吗?
- 我正在尝试一个傻瓜 C++ 练习,我遇到了一个错误,说类 'GraduateStudent' 没有任何名为 'advisor' 的字段
- 零四元数和任何向量都不为零的特征积,这是一个错误吗?
- 处理程序的模块列表中有一个错误的模块"WebSocketModule"
- 在 C++ 中使用 "transform" 会给出一个错误,指出这未在作用域中声明
- 在Cython中使用C库时,我遇到了一个错误
- 我需要帮助创建一个评分系统,但它一直给我一个错误,注释掉的整数是给我带来麻烦的部分
- 我试图用c++编写递归fibonacci序列,但当我编译时,我遇到了一个错误
- 从system()调用G++会返回一个错误
- 在Visual Studio中,与std::async一起使用时不调用"thread_local"变量"析构函数,这是一个错误吗?
- 我收到一个错误无效的操作数,类型为 const char [42] 和二进制"运算符+"的双倍数
- 使用声明:GCC 和 Clang 的另一个错误?
- 全球免费给出一个错误.调试器不解释
- 相对于继承的构造函数,gcc 编译器是否还有一个错误?
- 为什么直接传递"this"指针来存档是一个错误,而另一个相同类型的指针是可以的?
- 为什么第三板有一个错误
- 如何编写一个错误结构,该结构可以包含不同的强键枚举作为错误代码
- 使用本地类型声明的G lambda被使用但从未定义 - 确实是一个错误
- 我需要在 Android Studio 中构建 NDK. 但它返回一个错误