【问题标题】:How to retrive pair of points stored in list如何检索存储在列表中的点对
【发布时间】:2013-10-03 15:47:21
【问题描述】:

我在 QT Creator 中工作。我想找到两点的斜率。对于两点 A(x1,y1) , B(x2,y2) 使用斜率公式

m = (y2-y1)/(x2-x1)。

问题:

点存储在列表 p 中。我想从这个列表中一次取两个点,然后找到两个点的斜率直到列表末尾。

例如,如果列表包含 5 个点 {a,b,c,d,e}。我想找到斜率 1. ab 2. 公元前 3. 光盘 4. 去

代码:

    QList< QgsPoint > p;
    {
    /* some Process */ 

     p.push_front( path->vertex( e.inVertex() ).point() ); /* some points are added to list*/
    }

    QList< QgsPoint>::iterator it;   
    for ( it = p.begin(); it != p.end(); ++it )
    {
    mrbPath->addPoint( *it );
    }

【问题讨论】:

  • for(itf = p.begin(), its = p.begin()+1; its != p.end(); ++itf, ++its) { m = (its ->y - itf->y)/(its->x - itf->x); }

标签: c++ qt list iterator qgis


【解决方案1】:

你可以使用java-style iterator:

QListIterator<QgsPoint> i(p);
while(i.hasNext())
{
    if(!i.hasPrevious())
    {
        i.next();
        continue;
    }
    m = (i.peekNext().y() - i.peekPrevious().y()) / (i.peekNext().x()-i.peekPrevious().x());
    i.next();
}

【讨论】:

    【解决方案2】:

    @itwasntpete 的评论是正确的答案。但是,如果您愿意,可以使用一个迭代器来完成:

    for( QList< QgsPoint >::iterator it = p.empty() ? p.begin() - 1 : p.begin(); it + 1 != p.end(); ++it )
    {
        const float slope = ( it[1].y() - it->y() ) / ( it[1].x() - it->x() );
        //Do something with slope here
    }
    

    【讨论】:

      【解决方案3】:

      你可以在没有迭代器的情况下做到这一点。也许你会发现这段代码更干净:

      for(int i = 0; i <= list.count() - 2; i++) {
        QgsPoint a = list[i], b = list[i + 1];
        //...
      }
      

      【讨论】:

      • 谢谢。请解释为什么 list.count() - 2 ?正如我之前所说,我需要计算整个列表的斜率。
      • list.count() - 2 是列表倒数第二项的索引。此项应为最后一个 (a, b) 对中的 a
      猜你喜欢
      • 1970-01-01
      • 2020-07-22
      • 2011-12-17
      • 2019-10-06
      • 2014-01-31
      • 2018-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多