From 6fdacb0759144b13099867b590a548db7df7ae01 Mon Sep 17 00:00:00 2001 From: Peter Nelson Date: Wed, 1 Oct 2025 21:54:40 +0100 Subject: [PATCH] Codechange: Use find/find_if to search for rail/road types by label. Replaces manual loops. --- src/rail.cpp | 16 ++++++---------- src/road.cpp | 16 ++++++---------- 2 files changed, 12 insertions(+), 20 deletions(-) diff --git a/src/rail.cpp b/src/rail.cpp index 7e7174fef2..b977c1c963 100644 --- a/src/rail.cpp +++ b/src/rail.cpp @@ -194,20 +194,16 @@ RailTypes GetRailTypes(bool introduces) */ RailType GetRailTypeByLabel(RailTypeLabel label, bool allow_alternate_labels) { + extern RailTypeInfo _railtypes[RAILTYPE_END]; if (label == 0) return INVALID_RAILTYPE; - /* Loop through each rail type until the label is found */ - for (RailType r = RAILTYPE_BEGIN; r != RAILTYPE_END; r++) { - const RailTypeInfo *rti = GetRailTypeInfo(r); - if (rti->label == label) return r; + auto it = std::ranges::find(_railtypes, label, &RailTypeInfo::label); + if (it == std::end(_railtypes) && allow_alternate_labels) { + /* Test if any rail type defines the label as an alternate. */ + it = std::ranges::find_if(_railtypes, [label](const RailTypeInfo &rti) { return rti.alternate_labels.contains(label); }); } - if (allow_alternate_labels) { - /* Test if any rail type defines the label as an alternate. */ - for (RailType r = RAILTYPE_BEGIN; r != RAILTYPE_END; r++) { - if (GetRailTypeInfo(r)->alternate_labels.contains(label)) return r; - } - } + if (it != std::end(_railtypes)) return it->Index(); /* No matching label was found, so it is invalid */ return INVALID_RAILTYPE; diff --git a/src/road.cpp b/src/road.cpp index 590abfa07c..18478e9598 100644 --- a/src/road.cpp +++ b/src/road.cpp @@ -264,20 +264,16 @@ RoadTypes GetRoadTypes(bool introduces) */ RoadType GetRoadTypeByLabel(RoadTypeLabel label, bool allow_alternate_labels) { + extern RoadTypeInfo _roadtypes[ROADTYPE_END]; if (label == 0) return INVALID_ROADTYPE; - /* Loop through each road type until the label is found */ - for (RoadType r = ROADTYPE_BEGIN; r != ROADTYPE_END; r++) { - const RoadTypeInfo *rti = GetRoadTypeInfo(r); - if (rti->label == label) return r; + auto it = std::ranges::find(_roadtypes, label, &RoadTypeInfo::label); + if (it == std::end(_roadtypes) && allow_alternate_labels) { + /* Test if any road type defines the label as an alternate. */ + it = std::ranges::find_if(_roadtypes, [label](const RoadTypeInfo &rti) { return rti.alternate_labels.contains(label); }); } - if (allow_alternate_labels) { - /* Test if any road type defines the label as an alternate. */ - for (RoadType r = ROADTYPE_BEGIN; r != ROADTYPE_END; r++) { - if (GetRoadTypeInfo(r)->alternate_labels.contains(label)) return r; - } - } + if (it != std::end(_roadtypes)) return it->Index(); /* No matching label was found, so it is invalid */ return INVALID_ROADTYPE;