简体   繁体   中英

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

如果我没有弄错,因为您使用的是模板参数,则需要在迭代器声明前加上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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM