STL 映射,使用类的迭代器和指针
STL map, using iterators and pointers of classes
我在使用迭代器访问地图中的数据时遇到问题。我想使用迭代器返回插入到映射中的所有值。但是,当我使用迭代器时,它不会确认它过去进入的类实例中的任何成员。
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;
}
编译器输出:
lab12main.cpp||In function `int main()':|
lab12main.cpp|69|error: 'struct std::pair<const std::string, MapVertex*>'
has no member named 'getText'|
||=== Build finished: 1 errors, 0 warnings ===|
在我的 MapVertex 类中有一个名为 getText() 的访问成员,它返回其中的数据。
要修复编译器错误,您需要执行it->second->getText()
,因为*iterator
是一个pair<string, MapVertex*>
。但是您的代码中还有其他问题。插入到映射中时,将局部变量的地址插入到映射中。当您尝试使用循环迭代映射时,此地址将无效for
。我建议您将地图声明为std::map<string, MyVertex>
这样当您将MyVertex的副本插入到地图中时
tmpVert
是问题所在。看,你在堆栈上创建它。它在每个for
循环结束时被销毁。
它被摧毁了。
因此,您的mapGraph
持有指向不存在对象的指针。
'struct std::pair' has no member named 'getText'
意味着迭代器返回的是 std::p air,而不是直接返回你的对象;对的第一个元素是键,第二个是值,所以你需要获取值,然后调用方法:it->second->method()
。
相关文章:
- std::vector::迭代器是否可以合法地作为指针
- 不明白迭代器,引用和指针失效,一个例子
- 为什么 vector 的随机访问迭代器给出与指针不同的内存地址?
- 在C++中释放内存期间,迭代器与指针有何不同
- 迭代器的指针操作问题
- 对于随机访问迭代器(矢量迭代器),迭代器C++样式指针吗?
- 专门C++使用指针值类型的通用迭代器的模板函数?
- 从 std::vector 迭代器中执行函数指针
- 使用 map<char,strring> 的迭代器返回指针 map<char,strring>*
- 迭代器是否分配内存(如指针)?
- 如何在C++中重新实现包含指针的 STL 容器的类的迭代器
- 向量<pointer>:插入(迭代器,指针)插入垃圾值
- 迭代器可以变成指针吗?
- 使用迭代器指针 (C++) 从对象指针列表中删除元素
- 迭代器指针不引用第一个元素
- "strong"迭代器指针/引用
- c++ 如何将迭代器指针传递给通过引用需要对象的函数
- 泛型迭代器/指针初始化
- 断言模板实参是一个迭代器/指针
- 将输入迭代器(指针)复制到vector