Reputation: 1524
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();
Upvotes: 2
Views: 8304
Reputation: 4468
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;
}
Upvotes: 1
Reputation: 44161
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();
Upvotes: 12
Reputation: 12268
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.)
Upvotes: 0