代码之家  ›  专栏  ›  技术社区  ›  genpfault

一次取两个迭代器?

  •  0
  • genpfault  · 技术社区  · 16 年前

    我经常这样表示和处理折线:

    typedef std::vector< Point_t > Polyline_t;
    
    double PolylineLength(const Polyline_t& line)
    {
        double len = 0.0;
        for( size_t i = 0; i < line.size()-1; ++i )
            len += (line[i+1]-line[i+0]).length();
        return len;
    }
    

    typedef std::list< Point_t > Polyline_t;
    typedef Polyline_t::const_iterator Polyline_t_cit;
    
    double PolylineLength(const Polyline_t& line)
    {
        double len = 0.0;
        Polyline_t_cit last = line.end();
        last--;
        for( Polyline_t_cit i = line.begin(); i != last; ++i )
        {
            const Point_t& beg = *i;
            const Point_T& end = *(++i);
            len += (end - beg).length();
            --i;
        }
        return len;
    }
    

    2 回复  |  直到 16 年前
        1
  •  8
  •   Johannes Schaub - litb    16 年前

    我会保留两个迭代器,然后检查第二个迭代器是否已达到 end 。这将使它不再需要双向迭代器:

    typedef std::list< Point_t > Polyline_t;
    typedef Polyline_t::const_iterator Polyline_t_cit;
    
    double PolylineLength(const Polyline_t& line)
    {
        double len = 0.0;
        Polyline_t_cit f = line.begin(), s(f), end = line.end();
        for(++s; s != end; ++f, ++s) {
            len += (*s - *f).length();
        }
        return len;
    }
    
        2
  •  1
  •   pingw33n    16 年前

    --i 紧接之前 ++i -两者都是不必要的。

    typedef std::list< Point_t > Polyline_t;
    typedef Polyline_t::const_iterator Polyline_t_cit;
    
    double PolylineLength(const Polyline_t& line)
    {
        double len = 0.0;
        Polyline_t_cit last = line.end();
        last--;
        for( Polyline_t_cit i = line.begin(); i != last; )
        {
            const Point_t& beg = *i;
            const Point_T& end = *(++i);
            len += (end - beg).length();
        }
        return len;
    }