声明 std::map 迭代器会导致一个奇怪的错误

Declaring a std::map iterator causes a weird error

本文关键字:一个 错误 map std 迭代器 声明      更新时间:2023-10-16

我只是想声明一个映射迭代器,但我收到一个编译错误,说"预期;在它之前"

我相信这是因为我没有包含整个 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:: 中,迭代器是嵌套在地图模板中的类型。

相关文章: