I am having trouble accessing data inside a map using an iterator. I want to return all of the values inserted into the map by using an iterator. However, when I use the iterator, it doesn’t acknowledge any of the members in the instance of the class it has been past into.
int main()
{
ifstream inputFile;
int numberOfVertices;
char filename[30];
string tmp;
//the class the holds the graph
map<string, MapVertex*> mapGraph;
//input the filename
cout << "Input the filename of the graph: ";
cin >> filename;
inputFile.open(filename);
if (inputFile.good())
{
inputFile >> numberOfVertices;
inputFile.ignore();
for (int count = 0; count < numberOfVertices; count++)
{
getline(inputFile, tmp);
cout << "COUNT: " << count << " VALUE: " << tmp << endl;
MapVertex tmpVert;
tmpVert.setText(tmp);
mapGraph[tmp]=&tmpVert;
}
string a;
string connectTo[2];
while (!inputFile.eof())
{
//connectTo[0] and connectTo[1] are two strings that are behaving as keys
MapVertex* pointTo;
pointTo = mapGraph[connectTo[0]];
pointTo->addNeighbor(mapGraph[connectTo[1]]);
//map.find(connectTo[0]).addNeighbor(map.find(connectTo[1]));
//cout << connectTo[0] << "," << connectTo[1] << endl;
}
map<string,MapVertex*>::iterator it;
for (it=mapGraph.begin(); it!=mapGraph.end(); it++)
{
cout << it->getText() << endl;
}
}
return 0;
}
Compiler output:
\lab12\main.cpp||In function `int main()':|
\lab12\main.cpp|69|error: 'struct std::pair<const std::string, MapVertex*>'
has no member named 'getText'|
||=== Build finished: 1 errors, 0 warnings ===|
There is an access member in my MapVertex class called getText() which returns the data that is inside it.
To fix the compiler error, you need to do
it->second->getText()as the*iteratoris apair<string, MapVertex*>. But there are other problems in your code. While inserting into the map, you are inserting the address of a local variable into it. This address will be invalid by the time you try to iterate the map usingforloop. I would suggest you to declare the map asstd::map<string, MyVertex>so that when you insert into the map a copy of the MyVertex is inserted into map.