c++ - STL Map - 显示 find() 函数指向的内容

标签 c++ dictionary stl iterator iostream

出于测试目的,我通过 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 , 和 secondvector<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/

相关文章:

c++ - 如何翻转像素数据的Y轴

c++ - C++ 中的一个非常大的 3D 数组

c# - 为什么我不能将 ToList() 与我的 KeyCollection 一起使用

java - 使用键或索引从 Java 中的数据类型检索值

python - 使用宽松字典映射列中的值

c++ - 初始化一个reference_wrapper数组

c++ - 在 Linux 中查找函数签名

c++ - 如何在标准 C++ 字符串中使用 3 和 4 字节的 Unicode 字符?

c++ - 用于删除一系列值的 STL 容器

c++ - 在排序的 STL 容器中查找给定键的 "best matching key"