出于测试目的,我通过 for
循环运行以下代码。实际上只有前三个键存在,并且 “找到记录” 与从 findVertex->first
检索到的键一起按预期显示。
- 我的问题是,我如何才能访问指向的第二个值?
findVertex->second
看起来很明显,但不起作用,因为第二个值是我创建的一个对象,它的声明在代码下方给出,如果它有任何用处的话。
for(int i = 0; i<10; i++)
{
map<int, vector<Vertex> >::const_iterator findVertex = vertexMap.find(i);
if(findVertex != vertexMap.end())
{
cout<<"\nRecord found: ";
cout<<findVertex->first;
cout<<findVertex->second; //does not work
}
else
cout<<"\nRecord not found";
}
类代码:
class Vertex
{
private:
int currentIndex;
double xPoint, yPoint, zPoint;
vector<double> attributes;
public:
friend istream& operator>>(istream&, Vertex &);
friend ostream& operator<<(ostream&, Vertex &);
};
谢谢
最佳答案
你的 map
是类型
map<int, vector<Vertex>>
这意味着 first
是一个 int
, 和 second
是vector<Vertex>
.
虽然您已经定义了 operator<<
对于 Vertex
, vector<Vertex>
没有这样的功能.你会遍历你的 vector
,如果你可以访问 C++11,你可以使用类似的东西
if(findVertex != vertexMap.end())
{
cout << "\nRecord found: ";
cout << findVertex->first << '\n';
for (auto const& vertex : findVertex->second)
{
cout << vertex << '\n';
}
}
如果您无法访问 C++11,您可以手动执行相同的想法
if(findVertex != vertexMap.end())
{
cout << "\nRecord found: ";
cout << findVertex->first << '\n';
for (vector<Vertex>::const_iterator itVertex = findVertex->second.cbegin();
itVertex != findVertex->second.cend();
++itVertex)
{
Vertex const& vertex = *itVertex;
cout << vertex << '\n';
}
}
关于c++ - STL Map - 显示 find() 函数指向的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30331309/