[gdal-dev] Use of C++ iterators in API

Even Rouault even.rouault at spatialys.com
Tue Apr 10 13:06:23 PDT 2018


Hi,

Just wanted to advertize the recent new introduction of C++ iterators over 
GDALDataset (to iterate over its bands, layers and features), OGRLayer (to 
iterate overs its features), OGRFeature (to iterate over its field values) and 
OGRGeometry (if you iterate over a OGRGeometryCollection, you get its members. 
If you iterate over a OGRPolygon, you get its rings, etc...)
Fields can also be get and set using the [] operator on a feature.

Taken from the updated API tutorial : http://gdal.org/ogr_apitut.html

#include "ogrsf_frmts.h"
int main()
{
    GDALAllRegister();
    GDALDatasetUniquePtr poDS(GDALDataset::Open( "point.shp", 
GDAL_OF_VECTOR));
    if( poDS == nullptr )
    {
        printf( "Open failed.\n" );
        exit( 1 );
    }
    for( auto&& poLayer: poDS->GetLayers() )
    {
        for( auto&& poFeature: *poLayer )
        {
            for( auto&& oField: *poFeature )
            {
                switch( oField.GetType() )
                {
                    case OFTInteger:
                        printf( "%d,", oField.GetInteger() );
                        break;
                    case OFTInteger64:
                        printf( CPL_FRMT_GIB ",", oField.GetInteger64() );
                        break;
                    case OFTReal:
                        printf( "%.3f,", oField.GetDouble() );
                        break;
                    case OFTString:
                        printf( "%s,", oField.GetString() );
                        break;
                    default:
                        printf( "%s,", oField.GetAsString() );
                        break;
                }
          }
     }
}

There's also a visitor over OGRGeometry subclasses that can make life easier
( http://gdal.org/classOGRDefaultConstGeometryVisitor.html )

The autotest cpp stuff starting at
https://github.com/OSGeo/gdal/blob/master/autotest/cpp/test_ogr.cpp#L963
should get a good picture of all the new API.

Even


-- 
Spatialys - Geospatial professional services
http://www.spatialys.com


More information about the gdal-dev mailing list