当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - 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"

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.

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();

网友答案:

If I'm not mistaken because you are using a template argument you need to prefix the iterator declaration with 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. You don't need to 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.)

分享给朋友:
您可能感兴趣的文章:
随机阅读: