[英]Declaring a std::map iterator causes a weird error
I am just trying to declare a map iterator but I get a compile error saying "expected ; before it" 我只是想声明一个map迭代器,但是我得到一个编译错误,说“预期;在它之前”
I believe it is because I haven't included the whole std namespace (using namespace std;) but I intentionally dont want to include all of it. 我相信这是因为我没有包含整个std命名空间(使用命名空间std;)但我故意不想包含所有这些。
My code: 我的代码:
#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;
};
I have tried this aswell but it doesn't work: 我试过这个但是它不起作用:
std::map <unsigned int, Object*>::std::iterator it = m.begin();
如果我没有弄错,因为您使用的是模板参数,则需要在迭代器声明前加上typename
。
typename std::map <unsigned int, Object*>::iterator it = m.begin();
What's your compiler and flag settings? 你的编译器和标志设置是什么? I was able to build this 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;
}
You don't say what compiler you're using, but just by cutting and pasting this into a new file, it compiles fine in VS2010. 你没有说你正在使用什么编译器,但只是通过将其剪切并粘贴到一个新文件中,它在VS2010中编译得很好。 You don't need to
using namespace std;
您不需要
using namespace std;
certainly.... 当然....
(And your wrinkle of putting another std:: before iterator was creative, but isn't correct. :-) You're specifying that the map class template is located in namespace std::, and iterator is a type that's nested within the map template.) (并且你在迭代器之前放置另一个std ::的皱纹是创造性的,但是不正确。:-)你指定地图类模板位于命名空间std ::中,而迭代器是嵌套在地图模板。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.