STL Map iterator compilation error

R

Rakesh Kumar

I am encountering the following issue with STL map iterator - wrapped
within a template. ( I am wrapping it withing a template since I want
to hide the map implementation from the user . At a later point - this
could be a custom hashmap (as opposed to rb-tree map that stl
provides ).



#include <string>
#include <map>
#include <iostream>

template<typename K, typename V> class TestMap
{

public:
void insert(const std::pair<K, V> & ap)
{
data.insert(ap);
}

void list()
{
std::map<K, V>::iterator it = data.begin();
//compiler errors here - error: expected
`;' before "it"

for (; it != data.end(); ++it)
{
std::cout << it->first << " --> " << it->second << "\n";
}
}

private:
std::map<K, V> data;
};

using std::string;

int main()
{
TestMap<std::string, int> data;

data.insert(std::pair<string, int >("Hello", 1));
data.insert(std::pair<string, int >("World", 1));
return EXIT_SUCCESS;
}


The compiler errors out with the following message.

test.cxx:17: error: expected `;' before "it"

Any idea if I am missing anything here.
 
R

red floyd

Rakesh said:
I am encountering the following issue with STL map iterator - wrapped
within a template. ( I am wrapping it withing a template since I want
to hide the map implementation from the user . At a later point - this
could be a custom hashmap (as opposed to rb-tree map that stl
provides ).



#include <string>
#include <map>
#include <iostream>

template<typename K, typename V> class TestMap
{

public:
void insert(const std::pair<K, V> & ap)
{
data.insert(ap);
}

void list()
{
typename std::map<K,V>::iterator it = data.begin();
 
R

Rakesh Kumar

typename std::map<K,V>::iterator it = data.begin();

std::map<K,V>::iterator is a dependent name, the compiler needs some
help to know it's a type.


Thanks redfloyd for the help.

Revised code that compiles:

#include <string>

#include <map>
#include <iostream>

template<typename K, typename V> class TestMap
{

public:
void insert(const std::pair<K, V> & ap)
{
data.insert(ap);
}

void list()
{
typename std::map<K, V>::iterator it = data.begin();
for (; it != data.end(); ++it)
{
std::cout << it->first << " --> " << it->second << "\n";
}
}

private:
std::map<K, V> data;
};

using std::string;

int main()
{
TestMap<std::string, int> data;

data.insert(std::pair<string, int >("Hello", 1));
data.insert(std::pair<string, int >("World", 1));
return EXIT_SUCCESS;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top