[英]Declaring a std::map iterator causes a weird error
我只是想聲明一個map迭代器,但是我得到一個編譯錯誤,說“預期;在它之前”
我相信這是因為我沒有包含整個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();
你的編譯器和標志設置是什么? 我能夠建立這個好。
// 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 ::中,而迭代器是嵌套在地圖模板。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.