开发者

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, Ob开发者_如何学编程ject*>::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.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜