【问题标题】:Iterating through all the members of a vector遍历向量的所有成员
【发布时间】:2011-08-04 13:24:35
【问题描述】:

我有两个structs 定义如下:

struct vertex
{
  double x;
  double y;
  double z;
};

struct finalVertex
{
  int n;
  vertex v;
};

我使用以下代码遍历列表并打印所有成员:

  vector<finalVertex> finalVertices;
  vector<finalVertex>::iterator ve;

  for ( ve = finalVertices.begin(); ve < finalVertices.end(); ve++ )
    {
      out << *(ve).v.x << *(ve).v.y << *(ve).v.z << endl;
    }

我收到以下错误代码:

main.cpp:651: 错误:'class __gnu_cxx::__normal_iterator >>' 没有 名为“v”的成员

访问集合元素的语法正确方法是什么?

【问题讨论】:

    标签: c++ vector compiler-errors iteration


    【解决方案1】:

    问题在于运算符优先级:写成(*ve).v.x 或更简单的ve-&gt;v.x

    除此之外,我建议您为您的vertex 结构覆盖operator &lt;&lt;,以使您的代码更具可读性:

    std::ostream& operator <<(std::ostream& out, vertex const& value) {
        return out << value.x << " " << value.y << " " << value.z;
    }
    

    然后像这样使用它:

    for ( ve = finalVertices.begin(); ve != finalVertices.end(); ve++ )
        out << ve->v << endl;
    

    【讨论】:

      【解决方案2】:

      你应该做的是:

      ve->v.x
      

      你还可以做的是:

      (*ve).v.x
      

      但它很糟糕。 :)

      【讨论】:

        【解决方案3】:
        out << *(ve).v.x << *(ve).v.y << *(ve).v.z << endl;
        

        您的*(ve).v.x 等同于*((ve).v.x)。你可能想要:

        out << (*ve).v.x << (*ve).v.y << (*ve).v.z << endl;
        

        或者:

        out << ve->v.x << ve->v.y << ve->v.z << endl;
        

        此外,您的循环没有达到应有的效率。不需要每次迭代都调用end(),并且迭代器的后增量可能比普通指针/整数要重得多,因此您应该尽可能习惯使用前增量:

        for ( ve = finalVertices.begin(), end = finalVertices.end(); ve != end; ++ve )
        

        【讨论】:

        • 嗯,你知道,end() 是内联的优化构建,不应该涉及任何典型容器的计算,所以...
        • @ypnos:可能,是的。但是那里有很多非典型容器。
        【解决方案4】:

        将取消引用移至括号内,如下所示:

        out << (*ve).v.x << (*ve).v.y << (*ve).v.z << endl;
        

        我还建议将ve &lt; finalVertices.end(); 更改为ve != finalVertices.end();

        【讨论】:

          【解决方案5】:
                  for ( ve = finalVertices.begin(); ve != finalVertices.end(); ++ve )
                  {
                      ve->v.x;
                  }
          

          【讨论】:

            【解决方案6】:

            你不应该写 已经 你必须写 ve != finalVertices.end()

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2015-03-09
              • 2011-06-27
              • 2015-07-24
              • 2019-06-23
              • 1970-01-01
              • 1970-01-01
              • 2013-10-11
              相关资源
              最近更新 更多