diff --git a/src/animated_tile.cpp b/src/animated_tile.cpp index 5204547dd3..e2a5553711 100644 --- a/src/animated_tile.cpp +++ b/src/animated_tile.cpp @@ -53,8 +53,8 @@ void AnimateAnimatedTiles() { PerformanceAccumulator framerate(PFE_GL_LANDSCAPE); - const TileIndex *ti = _animated_tiles.Begin(); - while (ti < _animated_tiles.End()) { + const TileIndex *ti = _animated_tiles.data(); + while (ti < _animated_tiles.data() + _animated_tiles.size()) { const TileIndex curr = *ti; AnimateTile(curr); /* During the AnimateTile call, DeleteAnimatedTile could have been called, diff --git a/src/autoreplace_gui.cpp b/src/autoreplace_gui.cpp index 5b6976e674..133e9fb382 100644 --- a/src/autoreplace_gui.cpp +++ b/src/autoreplace_gui.cpp @@ -183,8 +183,8 @@ class ReplaceVehicleWindow : public Window { this->vscroll[1]->SetCount(this->engines[1].size()); if (this->reset_sel_engine && this->sel_engine[1] != INVALID_ENGINE) { int position = 0; - for (EngineID *it = this->engines[1].Begin(); it != this->engines[1].End(); ++it) { - if (*it == this->sel_engine[1]) break; + for (EngineID &eid : this->engines[1]) { + if (eid == this->sel_engine[1]) break; ++position; } this->vscroll[1]->ScrollTowards(position); diff --git a/src/base_media_base.h b/src/base_media_base.h index bcffa11a08..5655401558 100644 --- a/src/base_media_base.h +++ b/src/base_media_base.h @@ -76,9 +76,9 @@ struct BaseSet { { free(this->name); - for (TranslatedStrings::iterator iter = this->description.Begin(); iter != this->description.End(); iter++) { - free(iter->first); - free(iter->second); + for (auto &pair : this->description) { + free(pair.first); + free(pair.second); } for (uint i = 0; i < NUM_FILES; i++) { @@ -122,16 +122,16 @@ struct BaseSet { { if (isocode != NULL) { /* First the full ISO code */ - for (TranslatedStrings::const_iterator iter = this->description.Begin(); iter != this->description.End(); iter++) { - if (strcmp(iter->first, isocode) == 0) return iter->second; + for (const auto &pair : this->description) { + if (strcmp(pair.first, isocode) == 0) return pair.second; } /* Then the first two characters */ - for (TranslatedStrings::const_iterator iter = this->description.Begin(); iter != this->description.End(); iter++) { - if (strncmp(iter->first, isocode, 2) == 0) return iter->second; + for (const auto &pair : this->description) { + if (strncmp(pair.first, isocode, 2) == 0) return pair.second; } } /* Then fall back */ - return this->description.Begin()->second; + return this->description.front().second; } /** diff --git a/src/company_gui.cpp b/src/company_gui.cpp index a705687b0c..6b67f373ba 100644 --- a/src/company_gui.cpp +++ b/src/company_gui.cpp @@ -640,11 +640,11 @@ private: void AddChildren(GUIGroupList *source, GroupID parent, int indent) { - for (const Group **g = source->Begin(); g != source->End(); g++) { - if ((*g)->parent != parent) continue; - this->groups.push_back(*g); + for (const Group *g : *source) { + if (g->parent != parent) continue; + this->groups.push_back(g); this->indents.push_back(indent); - AddChildren(source, (*g)->index, indent + 1); + AddChildren(source, g->index, indent + 1); } } diff --git a/src/console_cmds.cpp b/src/console_cmds.cpp index 85b2ddbb19..1d3e9c52c4 100644 --- a/src/console_cmds.cpp +++ b/src/console_cmds.cpp @@ -585,8 +585,8 @@ DEF_CONSOLE_CMD(ConBanList) IConsolePrint(CC_DEFAULT, "Banlist: "); uint i = 1; - for (char **iter = _network_ban_list.Begin(); iter != _network_ban_list.End(); iter++, i++) { - IConsolePrintF(CC_DEFAULT, " %d) %s", i, *iter); + for (char *entry : _network_ban_list) { + IConsolePrintF(CC_DEFAULT, " %d) %s", i, entry); } return true; diff --git a/src/core/pool_func.cpp b/src/core/pool_func.cpp index 97f9ad1c78..7a65bf77a4 100644 --- a/src/core/pool_func.cpp +++ b/src/core/pool_func.cpp @@ -31,10 +31,7 @@ */ /* static */ void PoolBase::Clean(PoolType pt) { - PoolVector *pools = PoolBase::GetPools(); - PoolBase **end = pools->End(); - for (PoolBase **ppool = pools->Begin(); ppool != end; ppool++) { - PoolBase *pool = *ppool; + for (PoolBase *pool : *PoolBase::GetPools()) { if (pool->type & pt) pool->CleanPool(); } } diff --git a/src/core/smallmap_type.hpp b/src/core/smallmap_type.hpp index 0917c5423c..8cc96302f3 100644 --- a/src/core/smallmap_type.hpp +++ b/src/core/smallmap_type.hpp @@ -55,12 +55,13 @@ struct SmallMap : SmallVector, S> { * @param key key to find * @return &Pair(key, data) if found, this->End() if not */ - inline const Pair *Find(const T &key) const + inline typename std::vector::const_iterator Find(const T &key) const { - for (uint i = 0; i < std::vector::size(); i++) { - if (key == std::vector::operator[](i).first) return &std::vector::operator[](i); + typename std::vector::const_iterator it; + for (it = std::vector::begin(); it != std::vector::end(); it++) { + if (key == it->first) return it; } - return this->End(); + return it; } /** @@ -114,7 +115,7 @@ struct SmallMap : SmallVector, S> { */ inline void Erase(Pair *pair) { - assert(pair >= this->Begin() && pair < this->End()); + assert(pair >= std::vector::data() && pair < this->End()); auto distance = pair - std::vector::data(); std::vector::erase(std::vector::begin() + distance); } @@ -166,7 +167,7 @@ struct SmallMap : SmallVector, S> { inline void SortByKey() { - QSortT(this->Begin(), std::vector::size(), KeySorter); + QSortT(std::vector::data(), std::vector::size(), KeySorter); } static int CDECL KeySorter(const Pair *a, const Pair *b) diff --git a/src/core/smallvec_type.hpp b/src/core/smallvec_type.hpp index 9162c17b99..5ec07f2f01 100644 --- a/src/core/smallvec_type.hpp +++ b/src/core/smallvec_type.hpp @@ -83,46 +83,6 @@ public: } ~SmallVector() = default; - - /** - * Get the pointer to the first item (const) - * - * @return the pointer to the first item - */ - inline const T *Begin() const - { - return std::vector::data(); - } - - /** - * Get the pointer to the first item - * - * @return the pointer to the first item - */ - inline T *Begin() - { - return std::vector::data(); - } - - /** - * Get the pointer behind the last valid item (const) - * - * @return the pointer behind the last valid item - */ - inline const T *End() const - { - return std::vector::data() + std::vector::size(); - } - - /** - * Get the pointer behind the last valid item - * - * @return the pointer behind the last valid item - */ - inline T *End() - { - return std::vector::data() + std::vector::size(); - } }; /** diff --git a/src/economy.cpp b/src/economy.cpp index 1f17612f7d..cab605f9af 100644 --- a/src/economy.cpp +++ b/src/economy.cpp @@ -1945,9 +1945,8 @@ void LoadUnloadStation(Station *st) } /* Call the production machinery of industries */ - const Industry * const *isend = _cargo_delivery_destinations.End(); - for (Industry **iid = _cargo_delivery_destinations.Begin(); iid != isend; iid++) { - TriggerIndustryProduction(*iid); + for (Industry *iid : _cargo_delivery_destinations) { + TriggerIndustryProduction(iid); } _cargo_delivery_destinations.clear(); } diff --git a/src/engine.cpp b/src/engine.cpp index 7412ec639c..044faa5713 100644 --- a/src/engine.cpp +++ b/src/engine.cpp @@ -511,12 +511,12 @@ void EngineOverrideManager::ResetToDefaultMapping() */ EngineID EngineOverrideManager::GetID(VehicleType type, uint16 grf_local_id, uint32 grfid) { - const EngineIDMapping *end = this->End(); EngineID index = 0; - for (const EngineIDMapping *eid = this->Begin(); eid != end; eid++, index++) { - if (eid->type == type && eid->grfid == grfid && eid->internal_id == grf_local_id) { + for (const EngineIDMapping &eid : *this) { + if (eid.type == type && eid.grfid == grfid && eid.internal_id == grf_local_id) { return index; } + index++; } return INVALID_ENGINE; } @@ -549,14 +549,14 @@ void SetupEngines() _engine_pool.CleanPool(); assert(_engine_mngr.size() >= _engine_mngr.NUM_DEFAULT_ENGINES); - const EngineIDMapping *end = _engine_mngr.End(); uint index = 0; - for (const EngineIDMapping *eid = _engine_mngr.Begin(); eid != end; eid++, index++) { + for (const EngineIDMapping &eid : _engine_mngr) { /* Assert is safe; there won't be more than 256 original vehicles * in any case, and we just cleaned the pool. */ assert(Engine::CanAllocateItem()); - const Engine *e = new Engine(eid->type, eid->internal_id); + const Engine *e = new Engine(eid.type, eid.internal_id); assert(e->index == index); + index++; } } diff --git a/src/engine_gui.cpp b/src/engine_gui.cpp index caf264e3d1..2c2440baf9 100644 --- a/src/engine_gui.cpp +++ b/src/engine_gui.cpp @@ -329,7 +329,7 @@ void EngList_Sort(GUIEngineList *el, EngList_SortTypeFunction compare) /* out-of-bounds access at the next line for size == 0 (even with operator[] at some systems) * generally, do not sort if there are less than 2 items */ if (size < 2) return; - QSortT(el->Begin(), size, compare); + QSortT(el->data(), size, compare); } /** diff --git a/src/fios.cpp b/src/fios.cpp index 6acb2d891e..c27e6d8afd 100644 --- a/src/fios.cpp +++ b/src/fios.cpp @@ -380,7 +380,7 @@ static void FiosGetFileList(SaveLoadOperation fop, fios_getlist_callback_proc *c { SortingBits order = _savegame_sort_order; _savegame_sort_order = SORT_BY_NAME | SORT_ASCENDING; - QSortT(file_list.files.Begin(), file_list.files.size(), CompareFiosItems); + QSortT(file_list.files.data(), file_list.files.size(), CompareFiosItems); _savegame_sort_order = order; } @@ -724,10 +724,10 @@ const char *FindScenario(const ContentInfo *ci, bool md5sum) { _scanner.Scan(false); - for (ScenarioIdentifier *id = _scanner.Begin(); id != _scanner.End(); id++) { - if (md5sum ? (memcmp(id->md5sum, ci->md5sum, sizeof(id->md5sum)) == 0) - : (id->scenid == ci->unique_id)) { - return id->filename; + for (ScenarioIdentifier &id : _scanner) { + if (md5sum ? (memcmp(id.md5sum, ci->md5sum, sizeof(id.md5sum)) == 0) + : (id.scenid == ci->unique_id)) { + return id.filename; } } diff --git a/src/fios.h b/src/fios.h index b1d260f841..cc69178137 100644 --- a/src/fios.h +++ b/src/fios.h @@ -139,7 +139,7 @@ public: */ inline const FiosItem *Begin() const { - return this->files.Begin(); + return this->files.data(); } /** @@ -148,7 +148,7 @@ public: */ inline const FiosItem *End() const { - return this->files.End(); + return this->Begin() + this->Length(); } /** diff --git a/src/fios_gui.cpp b/src/fios_gui.cpp index 49c1deac37..b5bcee5e8c 100644 --- a/src/fios_gui.cpp +++ b/src/fios_gui.cpp @@ -57,9 +57,8 @@ void LoadCheckData::Clear() this->current_date = 0; memset(&this->settings, 0, sizeof(this->settings)); - const CompanyPropertiesMap::iterator end = this->companies.End(); - for (CompanyPropertiesMap::iterator it = this->companies.Begin(); it != end; it++) { - delete it->second; + for (auto &pair : this->companies) { + delete pair.second; } companies.clear(); @@ -531,10 +530,9 @@ public: if (y > y_max) break; /* Companies / AIs */ - CompanyPropertiesMap::const_iterator end = _load_check_data.companies.End(); - for (CompanyPropertiesMap::const_iterator it = _load_check_data.companies.Begin(); it != end; it++) { - SetDParam(0, it->first + 1); - const CompanyProperties &c = *it->second; + for (auto &pair : _load_check_data.companies) { + SetDParam(0, pair.first + 1); + const CompanyProperties &c = *pair.second; if (c.name != NULL) { SetDParam(1, STR_JUST_RAW_STRING); SetDParamStr(2, c.name); diff --git a/src/fontcache.cpp b/src/fontcache.cpp index 2811f17989..82a441814f 100644 --- a/src/fontcache.cpp +++ b/src/fontcache.cpp @@ -411,8 +411,8 @@ FreeTypeFontCache::~FreeTypeFontCache() this->face = NULL; this->ClearFontCache(); - for (FontTable::iterator iter = this->font_tables.Begin(); iter != this->font_tables.End(); iter++) { - free(iter->second.second); + for (auto &iter : this->font_tables) { + free(iter.second.second); } } @@ -633,7 +633,7 @@ GlyphID FreeTypeFontCache::MapCharToGlyph(WChar key) const void *FreeTypeFontCache::GetFontTable(uint32 tag, size_t &length) { const FontTable::iterator iter = this->font_tables.Find(tag); - if (iter != this->font_tables.End()) { + if (iter != this->font_tables.data() + this->font_tables.size()) { length = iter->second.first; return iter->second.second; } diff --git a/src/game/game_text.cpp b/src/game/game_text.cpp index 4d67b69553..d57b2bc77f 100644 --- a/src/game/game_text.cpp +++ b/src/game/game_text.cpp @@ -147,7 +147,7 @@ struct StringListReader : StringReader { * @param translation Are we reading a translation? */ StringListReader(StringData &data, const LanguageStrings *strings, bool master, bool translation) : - StringReader(data, strings->language, master, translation), p(strings->lines.Begin()), end(strings->lines.End()) + StringReader(data, strings->language, master, translation), p(strings->lines.data()), end(p + strings->lines.size()) { } @@ -318,13 +318,13 @@ void GameStrings::Compile() StringNameWriter id_writer(&this->string_names); id_writer.WriteHeader(data); - for (LanguageStrings **p = this->raw_strings.Begin(); p != this->raw_strings.End(); p++) { + for (LanguageStrings *p : this->raw_strings) { data.FreeTranslation(); - StringListReader translation_reader(data, *p, false, strcmp((*p)->language, "english") != 0); + StringListReader translation_reader(data, p, false, strcmp(p->language, "english") != 0); translation_reader.ParseFile(); if (_errors != 0) throw std::exception(); - this->compiled_strings.push_back(new LanguageStrings((*p)->language)); + this->compiled_strings.push_back(new LanguageStrings(p->language)); TranslationWriter writer(&this->compiled_strings.back()->lines); writer.WriteLang(data); } @@ -360,10 +360,11 @@ void RegisterGameTranslation(Squirrel *engine) if (SQ_FAILED(sq_get(vm, -2))) return; int idx = 0; - for (const char * const *p = _current_data->string_names.Begin(); p != _current_data->string_names.End(); p++, idx++) { - sq_pushstring(vm, *p, -1); + for (const char * const p : _current_data->string_names) { + sq_pushstring(vm, p, -1); sq_pushinteger(vm, idx); sq_rawset(vm, -3); + idx++; } sq_pop(vm, 2); @@ -391,9 +392,9 @@ void ReconsiderGameScriptLanguage() assert(language != NULL); language++; - for (LanguageStrings **p = _current_data->compiled_strings.Begin(); p != _current_data->compiled_strings.End(); p++) { - if (strcmp((*p)->language, language) == 0) { - _current_data->cur_language = *p; + for (LanguageStrings *p : _current_data->compiled_strings) { + if (strcmp(p->language, language) == 0) { + _current_data->cur_language = p; return; } } diff --git a/src/gfx.cpp b/src/gfx.cpp index dad675772a..df3e5ccb6b 100644 --- a/src/gfx.cpp +++ b/src/gfx.cpp @@ -511,7 +511,7 @@ int DrawString(int left, int right, int top, const char *str, TextColour colour, Layouter layout(str, INT32_MAX, colour, fontsize); if (layout.size() == 0) return 0; - return DrawLayoutLine(*layout.Begin(), top, left, right, align, underline, true); + return DrawLayoutLine(layout.front(), top, left, right, align, underline, true); } /** @@ -647,8 +647,7 @@ int DrawStringMultiLine(int left, int right, int top, int bottom, const char *st int last_line = top; int first_line = bottom; - for (const ParagraphLayouter::Line **iter = layout.Begin(); iter != layout.End(); iter++) { - const ParagraphLayouter::Line *line = *iter; + for (const ParagraphLayouter::Line *line : layout) { int line_height = line->GetLeading(); if (y >= top && y < bottom) { diff --git a/src/gfx_layout.cpp b/src/gfx_layout.cpp index ee0ba15332..6d4759cfbd 100644 --- a/src/gfx_layout.cpp +++ b/src/gfx_layout.cpp @@ -196,13 +196,13 @@ public: /* ICU's ParagraphLayout cannot handle empty strings, so fake one. */ buff[0] = ' '; length = 1; - fontMapping.End()[-1].first++; + fontMapping.back().first++; } /* Fill ICU's FontRuns with the right data. */ icu::FontRuns runs(fontMapping.size()); - for (FontMap::iterator iter = fontMapping.Begin(); iter != fontMapping.End(); iter++) { - runs.add(iter->second, iter->first); + for (auto &pair : fontMapping) { + runs.add(pair.second, pair.first); } LEErrorCode status = LE_NO_ERROR; @@ -419,8 +419,8 @@ int FallbackParagraphLayout::FallbackVisualRun::GetLeading() const int FallbackParagraphLayout::FallbackLine::GetLeading() const { int leading = 0; - for (const FallbackVisualRun * const *run = this->Begin(); run != this->End(); run++) { - leading = max(leading, (*run)->GetLeading()); + for (const FallbackVisualRun * const &run : *this) { + leading = max(leading, run->GetLeading()); } return leading; @@ -498,12 +498,12 @@ const ParagraphLayouter::Line *FallbackParagraphLayout::NextLine(int max_width) if (*this->buffer == '\0') { /* Only a newline. */ this->buffer = NULL; - l->push_back(new FallbackVisualRun(this->runs.Begin()->second, this->buffer, 0, 0)); + l->push_back(new FallbackVisualRun(this->runs.front().second, this->buffer, 0, 0)); return l; } int offset = this->buffer - this->buffer_begin; - FontMap::iterator iter = this->runs.Begin(); + FontMap::iterator iter = this->runs.data(); while (iter->first <= offset) { iter++; assert(iter != this->runs.End()); @@ -733,9 +733,9 @@ Layouter::Layouter(const char *str, int maxw, TextColour colour, FontSize fontsi Dimension Layouter::GetBounds() { Dimension d = { 0, 0 }; - for (const ParagraphLayouter::Line **l = this->Begin(); l != this->End(); l++) { - d.width = max(d.width, (*l)->GetWidth()); - d.height += (*l)->GetLeading(); + for (const ParagraphLayouter::Line *l : *this) { + d.width = max(d.width, l->GetWidth()); + d.height += l->GetLeading(); } return d; } @@ -757,12 +757,12 @@ Point Layouter::GetCharPosition(const char *ch) const size_t len = Utf8Decode(&c, str); if (c == '\0' || c == '\n') break; str += len; - index += (*this->Begin())->GetInternalCharLength(c); + index += this->front()->GetInternalCharLength(c); } if (str == ch) { /* Valid character. */ - const ParagraphLayouter::Line *line = *this->Begin(); + const ParagraphLayouter::Line *line = this->front(); /* Pointer to the end-of-string/line marker? Return total line width. */ if (*ch == '\0' || *ch == '\n') { @@ -795,7 +795,7 @@ Point Layouter::GetCharPosition(const char *ch) const */ const char *Layouter::GetCharAtPosition(int x) const { - const ParagraphLayouter::Line *line = *this->Begin(); + const ParagraphLayouter::Line *line = this->front(); for (int run_index = 0; run_index < line->CountRuns(); run_index++) { const ParagraphLayouter::VisualRun *run = line->GetVisualRun(run_index); @@ -844,8 +844,8 @@ Font *Layouter::GetFont(FontSize size, TextColour colour) */ void Layouter::ResetFontCache(FontSize size) { - for (FontColourMap::iterator it = fonts[size].Begin(); it != fonts[size].End(); ++it) { - delete it->second; + for (auto &pair : fonts[size]) { + delete pair.second; } fonts[size].clear(); diff --git a/src/group_gui.cpp b/src/group_gui.cpp index eb7aac0b71..59b5112ff1 100644 --- a/src/group_gui.cpp +++ b/src/group_gui.cpp @@ -127,11 +127,11 @@ private: void AddChildren(GUIGroupList *source, GroupID parent, int indent) { - for (const Group **g = source->Begin(); g != source->End(); g++) { - if ((*g)->parent != parent) continue; - this->groups.push_back(*g); + for (const Group *g : *source) { + if (g->parent != parent) continue; + this->groups.push_back(g); this->indents.push_back(indent); - AddChildren(source, (*g)->index, indent + 1); + AddChildren(source, g->index, indent + 1); } } diff --git a/src/hotkeys.cpp b/src/hotkeys.cpp index 39cf4c0a1a..0acc11c473 100644 --- a/src/hotkeys.cpp +++ b/src/hotkeys.cpp @@ -316,11 +316,11 @@ static void SaveLoadHotkeys(bool save) IniFile *ini = new IniFile(); ini->LoadFromDisk(_hotkeys_file, NO_DIRECTORY); - for (HotkeyList **list = _hotkey_lists->Begin(); list != _hotkey_lists->End(); ++list) { + for (HotkeyList *list : *_hotkey_lists) { if (save) { - (*list)->Save(ini); + list->Save(ini); } else { - (*list)->Load(ini); + list->Load(ini); } } @@ -343,11 +343,11 @@ void SaveHotkeysToConfig() void HandleGlobalHotkeys(WChar key, uint16 keycode) { - for (HotkeyList **list = _hotkey_lists->Begin(); list != _hotkey_lists->End(); ++list) { - if ((*list)->global_hotkey_handler == NULL) continue; + for (HotkeyList *list : *_hotkey_lists) { + if (list->global_hotkey_handler == NULL) continue; - int hotkey = (*list)->CheckMatch(keycode, true); - if (hotkey >= 0 && ((*list)->global_hotkey_handler(hotkey) == ES_HANDLED)) return; + int hotkey = list->CheckMatch(keycode, true); + if (hotkey >= 0 && (list->global_hotkey_handler(hotkey) == ES_HANDLED)) return; } } diff --git a/src/music/dmusic.cpp b/src/music/dmusic.cpp index a03a6ec57e..241ab191bf 100644 --- a/src/music/dmusic.cpp +++ b/src/music/dmusic.cpp @@ -751,7 +751,7 @@ static void MidiThreadProc(void *) block_time = playback_start_time + block.realtime * MIDITIME_TO_REFTIME; DEBUG(driver, 9, "DMusic thread: Streaming block " PRINTF_SIZE " (cur=" OTTD_PRINTF64 ", block=" OTTD_PRINTF64 ")", current_block, (long long)(current_time / MS_TO_REFTIME), (long long)(block_time / MS_TO_REFTIME)); - byte *data = block.data.Begin(); + byte *data = block.data.data(); size_t remaining = block.data.size(); byte last_status = 0; while (remaining > 0) { diff --git a/src/music/midifile.cpp b/src/music/midifile.cpp index 82649679fa..97fb2edf80 100644 --- a/src/music/midifile.cpp +++ b/src/music/midifile.cpp @@ -336,7 +336,7 @@ static bool FixupMidiData(MidiFile &target) last_ticktime = block.ticktime; } else { byte *datadest = grow(merged_blocks.back().data, block.data.size()); - memcpy(datadest, block.data.Begin(), block.data.size()); + memcpy(datadest, block.data.data(), block.data.size()); } } std::swap(merged_blocks, target.blocks); @@ -940,8 +940,8 @@ bool MidiFile::WriteSMF(const char *filename) } /* Write each block data command */ - byte *dp = block.data.Begin(); - while (dp < block.data.End()) { + byte *dp = block.data.data(); + while (dp < block.data.data() + block.data.size()) { /* Always zero delta time inside blocks */ if (needtime) { fputc(0, f); diff --git a/src/music/win32_m.cpp b/src/music/win32_m.cpp index 6d88af4a3c..18a3bce3e7 100644 --- a/src/music/win32_m.cpp +++ b/src/music/win32_m.cpp @@ -229,7 +229,7 @@ void CALLBACK TimerCallback(UINT uTimerID, UINT, DWORD_PTR dwUser, DWORD_PTR, DW break; } - byte *data = block.data.Begin(); + byte *data = block.data.data(); size_t remaining = block.data.size(); byte last_status = 0; while (remaining > 0) { diff --git a/src/network/core/host.cpp b/src/network/core/host.cpp index b1ed71e926..35c7ce8ae8 100644 --- a/src/network/core/host.cpp +++ b/src/network/core/host.cpp @@ -200,8 +200,8 @@ void NetworkFindBroadcastIPs(NetworkAddressList *broadcast) /* Now display to the debug all the detected ips */ DEBUG(net, 3, "Detected broadcast addresses:"); int i = 0; - for (NetworkAddress *addr = broadcast->Begin(); addr != broadcast->End(); addr++) { - addr->SetPort(NETWORK_DEFAULT_PORT); - DEBUG(net, 3, "%d) %s", i++, addr->GetHostname()); + for (NetworkAddress &addr : *broadcast) { + addr.SetPort(NETWORK_DEFAULT_PORT); + DEBUG(net, 3, "%d) %s", i++, addr.GetHostname()); } } diff --git a/src/network/core/tcp_connect.cpp b/src/network/core/tcp_connect.cpp index f3dc2cb9aa..d699cf60d0 100644 --- a/src/network/core/tcp_connect.cpp +++ b/src/network/core/tcp_connect.cpp @@ -93,5 +93,5 @@ void TCPConnecter::Connect() /** Kill all connection attempts. */ /* static */ void TCPConnecter::KillAll() { - for (TCPConnecter **iter = _tcp_connecters.Begin(); iter != _tcp_connecters.End(); iter++) (*iter)->killed = true; + for (TCPConnecter *conn : _tcp_connecters) conn->killed = true; } diff --git a/src/network/core/tcp_http.cpp b/src/network/core/tcp_http.cpp index abec3fbc87..cec77fb147 100644 --- a/src/network/core/tcp_http.cpp +++ b/src/network/core/tcp_http.cpp @@ -303,8 +303,8 @@ int NetworkHTTPSocketHandler::Receive() struct timeval tv; FD_ZERO(&read_fd); - for (NetworkHTTPSocketHandler **iter = _http_connections.Begin(); iter < _http_connections.End(); iter++) { - FD_SET((*iter)->sock, &read_fd); + for (NetworkHTTPSocketHandler *handler : _http_connections) { + FD_SET(handler->sock, &read_fd); } tv.tv_sec = tv.tv_usec = 0; // don't block at all. diff --git a/src/network/core/tcp_listen.h b/src/network/core/tcp_listen.h index 55594070be..744f8841fd 100644 --- a/src/network/core/tcp_listen.h +++ b/src/network/core/tcp_listen.h @@ -54,13 +54,13 @@ public: /* Check if the client is banned */ bool banned = false; - for (char **iter = _network_ban_list.Begin(); iter != _network_ban_list.End(); iter++) { - banned = address.IsInNetmask(*iter); + for (char *entry : _network_ban_list) { + banned = address.IsInNetmask(entry); if (banned) { Packet p(Tban_packet); p.PrepareToSend(); - DEBUG(net, 1, "[%s] Banned ip tried to join (%s), refused", Tsocket::GetName(), *iter); + DEBUG(net, 1, "[%s] Banned ip tried to join (%s), refused", Tsocket::GetName(), entry); if (send(s, (const char*)p.buffer, p.size, 0) < 0) { DEBUG(net, 0, "send failed with error %d", GET_LAST_ERROR()); @@ -111,16 +111,16 @@ public: } /* take care of listener port */ - for (SocketList::iterator s = sockets.Begin(); s != sockets.End(); s++) { - FD_SET(s->second, &read_fd); + for (auto &s : sockets) { + FD_SET(s.second, &read_fd); } tv.tv_sec = tv.tv_usec = 0; // don't block at all. if (select(FD_SETSIZE, &read_fd, &write_fd, NULL, &tv) < 0) return false; /* accept clients.. */ - for (SocketList::iterator s = sockets.Begin(); s != sockets.End(); s++) { - if (FD_ISSET(s->second, &read_fd)) AcceptClient(s->second); + for (auto &s : sockets) { + if (FD_ISSET(s.second, &read_fd)) AcceptClient(s.second); } /* read stuff from clients */ @@ -145,8 +145,8 @@ public: NetworkAddressList addresses; GetBindAddresses(&addresses, port); - for (NetworkAddress *address = addresses.Begin(); address != addresses.End(); address++) { - address->Listen(SOCK_STREAM, &sockets); + for (NetworkAddress &address : addresses) { + address.Listen(SOCK_STREAM, &sockets); } if (sockets.size() == 0) { @@ -161,8 +161,8 @@ public: /** Close the sockets we're listening on. */ static void CloseListeners() { - for (SocketList::iterator s = sockets.Begin(); s != sockets.End(); s++) { - closesocket(s->second); + for (auto &s : sockets) { + closesocket(s.second); } sockets.clear(); DEBUG(net, 1, "[%s] closed listeners", Tsocket::GetName()); diff --git a/src/network/core/udp.cpp b/src/network/core/udp.cpp index 7babf78d69..70bb0b9f05 100644 --- a/src/network/core/udp.cpp +++ b/src/network/core/udp.cpp @@ -25,8 +25,8 @@ NetworkUDPSocketHandler::NetworkUDPSocketHandler(NetworkAddressList *bind) { if (bind != NULL) { - for (NetworkAddress *addr = bind->Begin(); addr != bind->End(); addr++) { - this->bind.push_back(*addr); + for (NetworkAddress &addr : *bind) { + this->bind.push_back(addr); } } else { /* As hostname NULL and port 0/NULL don't go well when @@ -47,8 +47,8 @@ bool NetworkUDPSocketHandler::Listen() /* Make sure socket is closed */ this->Close(); - for (NetworkAddress *addr = this->bind.Begin(); addr != this->bind.End(); addr++) { - addr->Listen(SOCK_DGRAM, &this->sockets); + for (NetworkAddress &addr : this->bind) { + addr.Listen(SOCK_DGRAM, &this->sockets); } return this->sockets.size() != 0; @@ -59,8 +59,8 @@ bool NetworkUDPSocketHandler::Listen() */ void NetworkUDPSocketHandler::Close() { - for (SocketList::iterator s = this->sockets.Begin(); s != this->sockets.End(); s++) { - closesocket(s->second); + for (auto &s : this->sockets) { + closesocket(s.second); } this->sockets.clear(); } @@ -82,26 +82,26 @@ void NetworkUDPSocketHandler::SendPacket(Packet *p, NetworkAddress *recv, bool a { if (this->sockets.size() == 0) this->Listen(); - for (SocketList::iterator s = this->sockets.Begin(); s != this->sockets.End(); s++) { + for (auto &s : this->sockets) { /* Make a local copy because if we resolve it we cannot * easily unresolve it so we can resolve it later again. */ NetworkAddress send(*recv); /* Not the same type */ - if (!send.IsFamily(s->first.GetAddress()->ss_family)) continue; + if (!send.IsFamily(s.first.GetAddress()->ss_family)) continue; p->PrepareToSend(); if (broadcast) { /* Enable broadcast */ unsigned long val = 1; - if (setsockopt(s->second, SOL_SOCKET, SO_BROADCAST, (char *) &val, sizeof(val)) < 0) { + if (setsockopt(s.second, SOL_SOCKET, SO_BROADCAST, (char *) &val, sizeof(val)) < 0) { DEBUG(net, 1, "[udp] setting broadcast failed with: %i", GET_LAST_ERROR()); } } /* Send the buffer */ - int res = sendto(s->second, (const char*)p->buffer, p->size, 0, (const struct sockaddr *)send.GetAddress(), send.GetAddressLength()); + int res = sendto(s.second, (const char*)p->buffer, p->size, 0, (const struct sockaddr *)send.GetAddress(), send.GetAddressLength()); DEBUG(net, 7, "[udp] sendto(%s)", send.GetAddressAsString()); /* Check for any errors, but ignore it otherwise */ @@ -116,7 +116,7 @@ void NetworkUDPSocketHandler::SendPacket(Packet *p, NetworkAddress *recv, bool a */ void NetworkUDPSocketHandler::ReceivePackets() { - for (SocketList::iterator s = this->sockets.Begin(); s != this->sockets.End(); s++) { + for (auto &s : this->sockets) { for (int i = 0; i < 1000; i++) { // Do not infinitely loop when DoSing with UDP struct sockaddr_storage client_addr; memset(&client_addr, 0, sizeof(client_addr)); @@ -125,8 +125,8 @@ void NetworkUDPSocketHandler::ReceivePackets() socklen_t client_len = sizeof(client_addr); /* Try to receive anything */ - SetNonBlocking(s->second); // Some OSes seem to lose the non-blocking status of the socket - int nbytes = recvfrom(s->second, (char*)p.buffer, SEND_MTU, 0, (struct sockaddr *)&client_addr, &client_len); + SetNonBlocking(s.second); // Some OSes seem to lose the non-blocking status of the socket + int nbytes = recvfrom(s.second, (char*)p.buffer, SEND_MTU, 0, (struct sockaddr *)&client_addr, &client_len); /* Did we get the bytes for the base header of the packet? */ if (nbytes <= 0) break; // No data, i.e. no packet diff --git a/src/network/network.cpp b/src/network/network.cpp index 1ddd7478ce..be92623e41 100644 --- a/src/network/network.cpp +++ b/src/network/network.cpp @@ -632,8 +632,8 @@ void NetworkAddServer(const char *b) */ void GetBindAddresses(NetworkAddressList *addresses, uint16 port) { - for (char **iter = _network_bind_list.Begin(); iter != _network_bind_list.End(); iter++) { - addresses->emplace_back(*iter, port); + for (char *iter : _network_bind_list) { + addresses->emplace_back(iter, port); } /* No address, so bind to everything. */ diff --git a/src/network/network_client.cpp b/src/network/network_client.cpp index fff4dd328c..12aa3fc0ad 100644 --- a/src/network/network_client.cpp +++ b/src/network/network_client.cpp @@ -110,7 +110,7 @@ struct PacketReader : LoadFilter { { this->read_bytes = 0; - this->block = this->blocks.Begin(); + this->block = this->blocks.data(); this->buf = *this->block++; this->bufe = this->buf + CHUNK; } diff --git a/src/network/network_content.cpp b/src/network/network_content.cpp index 617a2bc6b6..003ffdb8ba 100644 --- a/src/network/network_content.cpp +++ b/src/network/network_content.cpp @@ -137,8 +137,7 @@ bool ClientNetworkContentSocketHandler::Receive_SERVER_INFO(Packet *p) if (ci->state == ContentInfo::UNSELECTED && ci->filesize == 0) ci->state = ContentInfo::DOES_NOT_EXIST; /* Do we already have a stub for this? */ - for (ContentIterator iter = this->infos.Begin(); iter != this->infos.End(); iter++) { - ContentInfo *ici = *iter; + for (ContentInfo *ici : this->infos) { if (ici->type == ci->type && ici->unique_id == ci->unique_id && memcmp(ci->md5sum, ici->md5sum, sizeof(ci->md5sum)) == 0) { /* Preserve the name if possible */ @@ -168,8 +167,8 @@ bool ClientNetworkContentSocketHandler::Receive_SERVER_INFO(Packet *p) this->infos.push_back(ci); /* Incoming data means that we might need to reconsider dependencies */ - for (ContentIterator iter = this->infos.Begin(); iter != this->infos.End(); iter++) { - this->CheckDependencyState(*iter); + for (ContentInfo *ici : this->infos) { + this->CheckDependencyState(ici); } this->OnReceiveContentInfo(ci); @@ -253,8 +252,7 @@ void ClientNetworkContentSocketHandler::RequestContentList(ContentVector *cv, bo Packet *p = new Packet(send_md5sum ? PACKET_CONTENT_CLIENT_INFO_EXTID_MD5 : PACKET_CONTENT_CLIENT_INFO_EXTID); p->Send_uint8(cv->size()); - for (ContentIterator iter = cv->Begin(); iter != cv->End(); iter++) { - const ContentInfo *ci = *iter; + for (const ContentInfo *ci : *cv) { p->Send_uint8((byte)ci->type); p->Send_uint32(ci->unique_id); if (!send_md5sum) continue; @@ -266,11 +264,9 @@ void ClientNetworkContentSocketHandler::RequestContentList(ContentVector *cv, bo this->SendPacket(p); - for (ContentIterator iter = cv->Begin(); iter != cv->End(); iter++) { - ContentInfo *ci = *iter; + for (ContentInfo *ci : *cv) { bool found = false; - for (ContentIterator iter2 = this->infos.Begin(); iter2 != this->infos.End(); iter2++) { - ContentInfo *ci2 = *iter2; + for (ContentInfo *ci2 : this->infos) { if (ci->type == ci2->type && ci->unique_id == ci2->unique_id && (!send_md5sum || memcmp(ci->md5sum, ci2->md5sum, sizeof(ci->md5sum)) == 0)) { found = true; @@ -296,8 +292,7 @@ void ClientNetworkContentSocketHandler::DownloadSelectedContent(uint &files, uin bytes = 0; ContentIDList content; - for (ContentIterator iter = this->infos.Begin(); iter != this->infos.End(); iter++) { - const ContentInfo *ci = *iter; + for (const ContentInfo *ci : this->infos) { if (!ci->IsSelected() || ci->state == ContentInfo::ALREADY_HERE) continue; content.push_back(ci->id); @@ -333,8 +328,8 @@ void ClientNetworkContentSocketHandler::DownloadSelectedContentHTTP(const Conten const char *lastof = content_request + bytes - 1; char *p = content_request; - for (const ContentID *id = content.Begin(); id != content.End(); id++) { - p += seprintf(p, lastof, "%d\n", *id); + for (const ContentID &id : content) { + p += seprintf(p, lastof, "%d\n", id); } this->http_response_index = -1; @@ -351,7 +346,7 @@ void ClientNetworkContentSocketHandler::DownloadSelectedContentHTTP(const Conten void ClientNetworkContentSocketHandler::DownloadSelectedContentFallback(const ContentIDList &content) { uint count = content.size(); - const ContentID *content_ids = content.Begin(); + const ContentID *content_ids = content.data(); this->Connect(); while (count > 0) { @@ -626,7 +621,7 @@ void ClientNetworkContentSocketHandler::OnReceiveData(const char *data, size_t l #define check_and_terminate(p) { check_not_null(p); *(p) = '\0'; } for (;;) { - char *str = this->http_response.Begin() + this->http_response_index; + char *str = this->http_response.data() + this->http_response_index; char *p = strchr(str, '\n'); check_and_terminate(p); @@ -713,7 +708,7 @@ ClientNetworkContentSocketHandler::~ClientNetworkContentSocketHandler() delete this->curInfo; if (this->curFile != NULL) fclose(this->curFile); - for (ContentIterator iter = this->infos.Begin(); iter != this->infos.End(); iter++) delete *iter; + for (ContentInfo *ci : this->infos) delete ci; } /** Connect to the content server. */ @@ -807,8 +802,7 @@ void ClientNetworkContentSocketHandler::DownloadContentInfo(ContentID cid) */ ContentInfo *ClientNetworkContentSocketHandler::GetContent(ContentID cid) { - for (ContentIterator iter = this->infos.Begin(); iter != this->infos.End(); iter++) { - ContentInfo *ci = *iter; + for (ContentInfo *ci : this->infos) { if (ci->id == cid) return ci; } return NULL; @@ -844,8 +838,7 @@ void ClientNetworkContentSocketHandler::Unselect(ContentID cid) /** Select everything we can select */ void ClientNetworkContentSocketHandler::SelectAll() { - for (ContentIterator iter = this->infos.Begin(); iter != this->infos.End(); iter++) { - ContentInfo *ci = *iter; + for (ContentInfo *ci : this->infos) { if (ci->state == ContentInfo::UNSELECTED) { ci->state = ContentInfo::SELECTED; this->CheckDependencyState(ci); @@ -856,8 +849,7 @@ void ClientNetworkContentSocketHandler::SelectAll() /** Select everything that's an update for something we've got */ void ClientNetworkContentSocketHandler::SelectUpgrade() { - for (ContentIterator iter = this->infos.Begin(); iter != this->infos.End(); iter++) { - ContentInfo *ci = *iter; + for (ContentInfo *ci : this->infos) { if (ci->state == ContentInfo::UNSELECTED && ci->upgrade) { ci->state = ContentInfo::SELECTED; this->CheckDependencyState(ci); @@ -868,8 +860,7 @@ void ClientNetworkContentSocketHandler::SelectUpgrade() /** Unselect everything that we've not downloaded so far. */ void ClientNetworkContentSocketHandler::UnselectAll() { - for (ContentIterator iter = this->infos.Begin(); iter != this->infos.End(); iter++) { - ContentInfo *ci = *iter; + for (ContentInfo *ci : this->infos) { if (ci->IsSelected() && ci->state != ContentInfo::ALREADY_HERE) ci->state = ContentInfo::UNSELECTED; } } @@ -899,8 +890,7 @@ void ClientNetworkContentSocketHandler::ToggleSelectedState(const ContentInfo *c */ void ClientNetworkContentSocketHandler::ReverseLookupDependency(ConstContentVector &parents, const ContentInfo *child) const { - for (ConstContentIterator iter = this->infos.Begin(); iter != this->infos.End(); iter++) { - const ContentInfo *ci = *iter; + for (const ContentInfo * const &ci : this->infos) { if (ci == child) continue; for (uint i = 0; i < ci->dependency_count; i++) { @@ -929,8 +919,8 @@ void ClientNetworkContentSocketHandler::ReverseLookupTreeDependency(ConstContent ConstContentVector parents; this->ReverseLookupDependency(parents, tree[i]); - for (ConstContentIterator piter = parents.Begin(); piter != parents.End(); piter++) { - include(tree, *piter); + for (const ContentInfo *ci : parents) { + include(tree, ci); } } } @@ -965,8 +955,7 @@ void ClientNetworkContentSocketHandler::CheckDependencyState(ContentInfo *ci) * we automatically selected them. */ ConstContentVector parents; this->ReverseLookupDependency(parents, ci); - for (ConstContentIterator iter = parents.Begin(); iter != parents.End(); iter++) { - const ContentInfo *c = *iter; + for (const ContentInfo *c : parents) { if (!c->IsSelected()) continue; this->Unselect(c->id); @@ -987,9 +976,9 @@ void ClientNetworkContentSocketHandler::CheckDependencyState(ContentInfo *ci) /* First check whether anything depends on us */ int sel_count = 0; bool force_selection = false; - for (ConstContentIterator iter = parents.Begin(); iter != parents.End(); iter++) { - if ((*iter)->IsSelected()) sel_count++; - if ((*iter)->state == ContentInfo::SELECTED) force_selection = true; + for (const ContentInfo *ci : parents) { + if (ci->IsSelected()) sel_count++; + if (ci->state == ContentInfo::SELECTED) force_selection = true; } if (sel_count == 0) { /* Nothing depends on us */ @@ -1004,8 +993,8 @@ void ClientNetworkContentSocketHandler::CheckDependencyState(ContentInfo *ci) this->ReverseLookupTreeDependency(parents, c); /* Is there anything that is "force" selected?, if so... we're done. */ - for (ConstContentIterator iter = parents.Begin(); iter != parents.End(); iter++) { - if ((*iter)->state != ContentInfo::SELECTED) continue; + for (const ContentInfo *ci : parents) { + if (ci->state != ContentInfo::SELECTED) continue; force_selection = true; break; @@ -1018,12 +1007,11 @@ void ClientNetworkContentSocketHandler::CheckDependencyState(ContentInfo *ci) * After that's done run over them once again to test their children * to unselect. Don't do it immediately because it'll do exactly what * we're doing now. */ - for (ConstContentIterator iter = parents.Begin(); iter != parents.End(); iter++) { - const ContentInfo *c = *iter; + for (const ContentInfo *c : parents) { if (c->state == ContentInfo::AUTOSELECTED) this->Unselect(c->id); } - for (ConstContentIterator iter = parents.Begin(); iter != parents.End(); iter++) { - this->CheckDependencyState(this->GetContent((*iter)->id)); + for (const ContentInfo *c : parents) { + this->CheckDependencyState(this->GetContent(c->id)); } } } @@ -1031,7 +1019,7 @@ void ClientNetworkContentSocketHandler::CheckDependencyState(ContentInfo *ci) /** Clear all downloaded content information. */ void ClientNetworkContentSocketHandler::Clear() { - for (ContentIterator iter = this->infos.Begin(); iter != this->infos.End(); iter++) delete *iter; + for (ContentInfo *c : this->infos) delete c; this->infos.clear(); this->requested.clear(); @@ -1041,37 +1029,37 @@ void ClientNetworkContentSocketHandler::Clear() void ClientNetworkContentSocketHandler::OnConnect(bool success) { - for (ContentCallback **iter = this->callbacks.Begin(); iter != this->callbacks.End(); /* nothing */) { + for (auto iter = this->callbacks.begin(); iter != this->callbacks.end(); /* nothing */) { ContentCallback *cb = *iter; cb->OnConnect(success); - if (iter != this->callbacks.End() && *iter == cb) iter++; + if (iter != this->callbacks.end() && *iter == cb) iter++; } } void ClientNetworkContentSocketHandler::OnDisconnect() { - for (ContentCallback **iter = this->callbacks.Begin(); iter != this->callbacks.End(); /* nothing */) { + for (auto iter = this->callbacks.begin(); iter != this->callbacks.end(); /* nothing */) { ContentCallback *cb = *iter; cb->OnDisconnect(); - if (iter != this->callbacks.End() && *iter == cb) iter++; + if (iter != this->callbacks.end() && *iter == cb) iter++; } } void ClientNetworkContentSocketHandler::OnReceiveContentInfo(const ContentInfo *ci) { - for (ContentCallback **iter = this->callbacks.Begin(); iter != this->callbacks.End(); /* nothing */) { + for (auto iter = this->callbacks.begin(); iter != this->callbacks.end(); /* nothing */) { ContentCallback *cb = *iter; cb->OnReceiveContentInfo(ci); - if (iter != this->callbacks.End() && *iter == cb) iter++; + if (iter != this->callbacks.end() && *iter == cb) iter++; } } void ClientNetworkContentSocketHandler::OnDownloadProgress(const ContentInfo *ci, int bytes) { - for (ContentCallback **iter = this->callbacks.Begin(); iter != this->callbacks.End(); /* nothing */) { + for (auto iter = this->callbacks.begin(); iter != this->callbacks.end(); /* nothing */) { ContentCallback *cb = *iter; cb->OnDownloadProgress(ci, bytes); - if (iter != this->callbacks.End() && *iter == cb) iter++; + if (iter != this->callbacks.end() && *iter == cb) iter++; } } @@ -1082,9 +1070,9 @@ void ClientNetworkContentSocketHandler::OnDownloadComplete(ContentID cid) ci->state = ContentInfo::ALREADY_HERE; } - for (ContentCallback **iter = this->callbacks.Begin(); iter != this->callbacks.End(); /* nothing */) { + for (auto iter = this->callbacks.begin(); iter != this->callbacks.end(); /* nothing */) { ContentCallback *cb = *iter; cb->OnDownloadComplete(cid); - if (iter != this->callbacks.End() && *iter == cb) iter++; + if (iter != this->callbacks.end() && *iter == cb) iter++; } } diff --git a/src/network/network_content.h b/src/network/network_content.h index 08e7755aae..26300c4ca2 100644 --- a/src/network/network_content.h +++ b/src/network/network_content.h @@ -131,11 +131,11 @@ public: /** Get the number of content items we know locally. */ uint Length() const { return this->infos.size(); } /** Get the begin of the content inf iterator. */ - ConstContentIterator Begin() const { return this->infos.Begin(); } + ConstContentIterator Begin() const { return this->infos.data(); } /** Get the nth position of the content inf iterator. */ ConstContentIterator Get(uint32 index) const { return this->infos.data() + index; } /** Get the end of the content inf iterator. */ - ConstContentIterator End() const { return this->infos.End(); } + ConstContentIterator End() const { return this->Begin() + this->Length(); } void Clear(); diff --git a/src/network/network_content_gui.cpp b/src/network/network_content_gui.cpp index 8e3ec9686a..9ea56d7471 100644 --- a/src/network/network_content_gui.cpp +++ b/src/network/network_content_gui.cpp @@ -176,8 +176,8 @@ public: ~NetworkContentDownloadStatusWindow() { TarScanner::Mode mode = TarScanner::NONE; - for (ContentType *iter = this->receivedTypes.Begin(); iter != this->receivedTypes.End(); iter++) { - switch (*iter) { + for (auto ctype : this->receivedTypes) { + switch (ctype) { case CONTENT_TYPE_AI: case CONTENT_TYPE_AI_LIBRARY: /* AI::Rescan calls the scanner. */ @@ -210,8 +210,8 @@ public: TarScanner::DoScan(mode); /* Tell all the backends about what we've downloaded */ - for (ContentType *iter = this->receivedTypes.Begin(); iter != this->receivedTypes.End(); iter++) { - switch (*iter) { + for (auto ctype : this->receivedTypes) { + switch (ctype) { case CONTENT_TYPE_AI: case CONTENT_TYPE_AI_LIBRARY: AI::Rescan(); @@ -333,8 +333,7 @@ class NetworkContentListWindow : public Window, ContentCallback { pos = strecpy(pos, "do=searchgrfid&q=", last); bool first = true; - for (ConstContentIterator iter = this->content.Begin(); iter != this->content.End(); iter++) { - const ContentInfo *ci = *iter; + for (const ContentInfo *ci : this->content) { if (ci->state != ContentInfo::DOES_NOT_EXIST) continue; if (!first) pos = strecpy(pos, ",", last); @@ -635,8 +634,13 @@ public: int sprite_y_offset = WD_MATRIX_TOP + (line_height - this->checkbox_size.height) / 2 - 1; int text_y_offset = WD_MATRIX_TOP + (line_height - FONT_HEIGHT_NORMAL) / 2; uint y = r.top; - int cnt = 0; - for (ConstContentIterator iter = this->content.data() + this->vscroll->GetPosition(); iter != this->content.End() && cnt < this->vscroll->GetCapacity(); iter++, cnt++) { + + auto iter = this->content.begin() + this->vscroll->GetPosition(); + auto end = iter + this->vscroll->GetCapacity(); + if (end > this->content.end()) + end = this->content.end(); + + for (/**/; iter != end; iter++) { const ContentInfo *ci = *iter; if (ci == this->selected) GfxFillRect(r.left + 1, y + 1, r.right - 1, y + this->resize.step_height - 1, PC_GREY); @@ -761,8 +765,7 @@ public: char buf[DRAW_STRING_BUFFER] = ""; char *p = buf; - for (ConstContentIterator iter = tree.Begin(); iter != tree.End(); iter++) { - const ContentInfo *ci = *iter; + for (const ContentInfo *ci : tree) { if (ci == this->selected || ci->state != ContentInfo::SELECTED) continue; p += seprintf(p, lastof(buf), buf == p ? "%s" : ", %s", ci->name); @@ -985,8 +988,7 @@ public: this->filesize_sum = 0; bool show_select_all = false; bool show_select_upgrade = false; - for (ConstContentIterator iter = this->content.Begin(); iter != this->content.End(); iter++) { - const ContentInfo *ci = *iter; + for (const ContentInfo *ci : this->content) { switch (ci->state) { case ContentInfo::SELECTED: case ContentInfo::AUTOSELECTED: @@ -1158,7 +1160,7 @@ void ShowNetworkContentListWindow(ContentVector *cv, ContentType type1, ContentT ShowErrorMessage(STR_CONTENT_NO_ZLIB, STR_CONTENT_NO_ZLIB_SUB, WL_ERROR); /* Connection failed... clean up the mess */ if (cv != NULL) { - for (ContentIterator iter = cv->Begin(); iter != cv->End(); iter++) delete *iter; + for (ContentInfo *ci : *cv) delete ci; } #endif /* WITH_ZLIB */ } diff --git a/src/network/network_gui.cpp b/src/network/network_gui.cpp index 7b65f6b0c3..a8dd2aa526 100644 --- a/src/network/network_gui.cpp +++ b/src/network/network_gui.cpp @@ -1045,8 +1045,8 @@ void ShowNetworkGameWindow() if (first) { first = false; /* Add all servers from the config file to our list. */ - for (char **iter = _network_host_list.Begin(); iter != _network_host_list.End(); iter++) { - NetworkAddServer(*iter); + for (char *iter : _network_host_list) { + NetworkAddServer(iter); } } @@ -1783,8 +1783,8 @@ struct NetworkClientListPopupWindow : Window { void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override { Dimension d = *size; - for (const ClientListAction *action = this->actions.Begin(); action != this->actions.End(); action++) { - d = maxdim(GetStringBoundingBox(action->name), d); + for (const ClientListAction &action : this->actions) { + d = maxdim(GetStringBoundingBox(action.name), d); } d.height *= this->actions.size(); @@ -1798,7 +1798,7 @@ struct NetworkClientListPopupWindow : Window { /* Draw the actions */ int sel = this->sel_index; int y = r.top + WD_FRAMERECT_TOP; - for (const ClientListAction *action = this->actions.Begin(); action != this->actions.End(); action++, y += FONT_HEIGHT_NORMAL) { + for (const ClientListAction &action : this->actions) { TextColour colour; if (sel-- == 0) { // Selected item, highlight it GfxFillRect(r.left + 1, y, r.right - 1, y + FONT_HEIGHT_NORMAL - 1, PC_BLACK); @@ -1807,7 +1807,8 @@ struct NetworkClientListPopupWindow : Window { colour = TC_BLACK; } - DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, action->name, colour); + DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, action.name, colour); + y += FONT_HEIGHT_NORMAL; } } diff --git a/src/network/network_server.cpp b/src/network/network_server.cpp index 8a1e75d2f2..36dde0f2cf 100644 --- a/src/network/network_server.cpp +++ b/src/network/network_server.cpp @@ -2095,8 +2095,8 @@ uint NetworkServerKickOrBanIP(const char *ip, bool ban) /* Add address to ban-list */ if (ban) { bool contains = false; - for (char **iter = _network_ban_list.Begin(); iter != _network_ban_list.End(); iter++) { - if (strcmp(*iter, ip) == 0) { + for (char *iter : _network_ban_list) { + if (strcmp(iter, ip) == 0) { contains = true; break; } diff --git a/src/network/network_udp.cpp b/src/network/network_udp.cpp index b416ee98e3..2d7ee2d3cf 100644 --- a/src/network/network_udp.cpp +++ b/src/network/network_udp.cpp @@ -495,12 +495,12 @@ void ClientNetworkUDPSocketHandler::HandleIncomingNetworkGameInfoGRFConfig(GRFCo /** Broadcast to all ips */ static void NetworkUDPBroadCast(NetworkUDPSocketHandler *socket) { - for (NetworkAddress *addr = _broadcast_list.Begin(); addr != _broadcast_list.End(); addr++) { + for (NetworkAddress &addr : _broadcast_list) { Packet p(PACKET_UDP_CLIENT_FIND_SERVER); - DEBUG(net, 4, "[udp] broadcasting to %s", addr->GetHostname()); + DEBUG(net, 4, "[udp] broadcasting to %s", addr.GetHostname()); - socket->SendPacket(&p, addr, true, true); + socket->SendPacket(&p, &addr, true, true); } } diff --git a/src/newgrf.cpp b/src/newgrf.cpp index 36a13aaaa3..8507d9d611 100644 --- a/src/newgrf.cpp +++ b/src/newgrf.cpp @@ -391,9 +391,8 @@ void CDECL grfmsg(int severity, const char *str, ...) */ static GRFFile *GetFileByGRFID(uint32 grfid) { - const GRFFile * const *end = _grf_files.End(); - for (GRFFile * const *file = _grf_files.Begin(); file != end; file++) { - if ((*file)->grfid == grfid) return *file; + for (GRFFile * const file : _grf_files) { + if (file->grfid == grfid) return file; } return NULL; } @@ -405,9 +404,8 @@ static GRFFile *GetFileByGRFID(uint32 grfid) */ static GRFFile *GetFileByFilename(const char *filename) { - const GRFFile * const *end = _grf_files.End(); - for (GRFFile * const *file = _grf_files.Begin(); file != end; file++) { - if (strcmp((*file)->filename, filename) == 0) return *file; + for (GRFFile * const file : _grf_files) { + if (strcmp(file->filename, filename) == 0) return file; } return NULL; } @@ -1923,7 +1921,7 @@ static ChangeInfoResult StationChangeInfo(uint stid, int numinfo, int prop, Byte /* On error, bail out immediately. Temporary GRF data was already freed */ if (_cur.skip_sprites < 0) return CIR_DISABLED; } - dts->Clone(tmp_layout.Begin()); + dts->Clone(tmp_layout.data()); } break; @@ -4826,7 +4824,7 @@ static void NewSpriteGroup(ByteReader *buf) group->num_adjusts = adjusts.size(); group->adjusts = MallocT(group->num_adjusts); - MemCpyT(group->adjusts, adjusts.Begin(), group->num_adjusts); + MemCpyT(group->adjusts, adjusts.data(), group->num_adjusts); std::vector ranges; ranges.resize(buf->ReadByte()); @@ -8094,9 +8092,8 @@ static void InitializeGRFSpecial() /** Reset and clear all NewGRF stations */ static void ResetCustomStations() { - const GRFFile * const *end = _grf_files.End(); - for (GRFFile **file = _grf_files.Begin(); file != end; file++) { - StationSpec **&stations = (*file)->stations; + for (GRFFile * const file : _grf_files) { + StationSpec **&stations = file->stations; if (stations == NULL) continue; for (uint i = 0; i < NUM_STATIONS_PER_GRF; i++) { if (stations[i] == NULL) continue; @@ -8129,9 +8126,8 @@ static void ResetCustomStations() /** Reset and clear all NewGRF houses */ static void ResetCustomHouses() { - const GRFFile * const *end = _grf_files.End(); - for (GRFFile **file = _grf_files.Begin(); file != end; file++) { - HouseSpec **&housespec = (*file)->housespec; + for (GRFFile * const file : _grf_files) { + HouseSpec **&housespec = file->housespec; if (housespec == NULL) continue; for (uint i = 0; i < NUM_HOUSES_PER_GRF; i++) { free(housespec[i]); @@ -8145,9 +8141,8 @@ static void ResetCustomHouses() /** Reset and clear all NewGRF airports */ static void ResetCustomAirports() { - const GRFFile * const *end = _grf_files.End(); - for (GRFFile **file = _grf_files.Begin(); file != end; file++) { - AirportSpec **aslist = (*file)->airportspec; + for (GRFFile * const file : _grf_files) { + AirportSpec **aslist = file->airportspec; if (aslist != NULL) { for (uint i = 0; i < NUM_AIRPORTS_PER_GRF; i++) { AirportSpec *as = aslist[i]; @@ -8166,10 +8161,10 @@ static void ResetCustomAirports() } } free(aslist); - (*file)->airportspec = NULL; + file->airportspec = NULL; } - AirportTileSpec **&airporttilespec = (*file)->airtspec; + AirportTileSpec **&airporttilespec = file->airtspec; if (airporttilespec != NULL) { for (uint i = 0; i < NUM_AIRPORTTILES_PER_GRF; i++) { free(airporttilespec[i]); @@ -8183,10 +8178,9 @@ static void ResetCustomAirports() /** Reset and clear all NewGRF industries */ static void ResetCustomIndustries() { - const GRFFile * const *end = _grf_files.End(); - for (GRFFile **file = _grf_files.Begin(); file != end; file++) { - IndustrySpec **&industryspec = (*file)->industryspec; - IndustryTileSpec **&indtspec = (*file)->indtspec; + for (GRFFile * const file : _grf_files) { + IndustrySpec **&industryspec = file->industryspec; + IndustryTileSpec **&indtspec = file->indtspec; /* We are verifiying both tiles and industries specs loaded from the grf file * First, let's deal with industryspec */ @@ -8223,9 +8217,8 @@ static void ResetCustomIndustries() /** Reset and clear all NewObjects */ static void ResetCustomObjects() { - const GRFFile * const *end = _grf_files.End(); - for (GRFFile **file = _grf_files.Begin(); file != end; file++) { - ObjectSpec **&objectspec = (*file)->objectspec; + for (GRFFile * const file : _grf_files) { + ObjectSpec **&objectspec = file->objectspec; if (objectspec == NULL) continue; for (uint i = 0; i < NUM_OBJECTS_PER_GRF; i++) { free(objectspec[i]); @@ -8239,9 +8232,8 @@ static void ResetCustomObjects() /** Reset and clear all NewGRFs */ static void ResetNewGRF() { - const GRFFile * const *end = _grf_files.End(); - for (GRFFile **file = _grf_files.Begin(); file != end; file++) { - delete *file; + for (GRFFile * const file : _grf_files) { + delete file; } _grf_files.clear(); @@ -8760,9 +8752,8 @@ static void FinaliseHouseArray() * On the other hand, why 1930? Just 'fix' the houses with the lowest * minimum introduction date to 0. */ - const GRFFile * const *end = _grf_files.End(); - for (GRFFile **file = _grf_files.Begin(); file != end; file++) { - HouseSpec **&housespec = (*file)->housespec; + for (GRFFile * const file : _grf_files) { + HouseSpec **&housespec = file->housespec; if (housespec == NULL) continue; for (int i = 0; i < NUM_HOUSES_PER_GRF; i++) { @@ -8774,7 +8765,7 @@ static void FinaliseHouseArray() const HouseSpec *next2 = (i + 2 < NUM_HOUSES_PER_GRF ? housespec[i + 2] : NULL); const HouseSpec *next3 = (i + 3 < NUM_HOUSES_PER_GRF ? housespec[i + 3] : NULL); - if (!IsHouseSpecValid(hs, next1, next2, next3, (*file)->filename)) continue; + if (!IsHouseSpecValid(hs, next1, next2, next3, file->filename)) continue; _house_mngr.SetEntitySpec(hs); } @@ -8823,10 +8814,9 @@ static void FinaliseHouseArray() */ static void FinaliseIndustriesArray() { - const GRFFile * const *end = _grf_files.End(); - for (GRFFile **file = _grf_files.Begin(); file != end; file++) { - IndustrySpec **&industryspec = (*file)->industryspec; - IndustryTileSpec **&indtspec = (*file)->indtspec; + for (GRFFile * const file : _grf_files) { + IndustrySpec **&industryspec = file->industryspec; + IndustryTileSpec **&indtspec = file->indtspec; if (industryspec != NULL) { for (int i = 0; i < NUM_INDUSTRYTYPES_PER_GRF; i++) { IndustrySpec *indsp = industryspec[i]; @@ -8894,9 +8884,8 @@ static void FinaliseIndustriesArray() */ static void FinaliseObjectsArray() { - const GRFFile * const *end = _grf_files.End(); - for (GRFFile **file = _grf_files.Begin(); file != end; file++) { - ObjectSpec **&objectspec = (*file)->objectspec; + for (GRFFile * const file : _grf_files) { + ObjectSpec **&objectspec = file->objectspec; if (objectspec != NULL) { for (int i = 0; i < NUM_OBJECTS_PER_GRF; i++) { if (objectspec[i] != NULL && objectspec[i]->grf_prop.grffile != NULL && objectspec[i]->enabled) { @@ -8914,9 +8903,8 @@ static void FinaliseObjectsArray() */ static void FinaliseAirportsArray() { - const GRFFile * const *end = _grf_files.End(); - for (GRFFile **file = _grf_files.Begin(); file != end; file++) { - AirportSpec **&airportspec = (*file)->airportspec; + for (GRFFile * const file : _grf_files) { + AirportSpec **&airportspec = file->airportspec; if (airportspec != NULL) { for (int i = 0; i < NUM_AIRPORTS_PER_GRF; i++) { if (airportspec[i] != NULL && airportspec[i]->enabled) { @@ -8925,7 +8913,7 @@ static void FinaliseAirportsArray() } } - AirportTileSpec **&airporttilespec = (*file)->airtspec; + AirportTileSpec **&airporttilespec = file->airtspec; if (airporttilespec != NULL) { for (uint i = 0; i < NUM_AIRPORTTILES_PER_GRF; i++) { if (airporttilespec[i] != NULL && airporttilespec[i]->enabled) { @@ -9286,10 +9274,9 @@ static void FinalisePriceBaseMultipliers() } /* Apply fallback prices for grf version < 8 */ - const GRFFile * const *end = _grf_files.End(); - for (GRFFile **file = _grf_files.Begin(); file != end; file++) { - if ((*file)->grf_version >= 8) continue; - PriceMultipliers &price_base_multipliers = (*file)->price_base_multipliers; + for (GRFFile * const file : _grf_files) { + if (file->grf_version >= 8) continue; + PriceMultipliers &price_base_multipliers = file->price_base_multipliers; for (Price p = PR_BEGIN; p < PR_END; p++) { Price fallback_price = _price_base_specs[p].fallback_price; if (fallback_price != INVALID_PRICE && price_base_multipliers[p] == INVALID_PRICE_MODIFIER) { @@ -9301,21 +9288,21 @@ static void FinalisePriceBaseMultipliers() } /* Decide local/global scope of price base multipliers */ - for (GRFFile **file = _grf_files.Begin(); file != end; file++) { - PriceMultipliers &price_base_multipliers = (*file)->price_base_multipliers; + for (GRFFile * const file : _grf_files) { + PriceMultipliers &price_base_multipliers = file->price_base_multipliers; for (Price p = PR_BEGIN; p < PR_END; p++) { if (price_base_multipliers[p] == INVALID_PRICE_MODIFIER) { /* No multiplier was set; set it to a neutral value */ price_base_multipliers[p] = 0; } else { - if (!HasBit((*file)->grf_features, _price_base_specs[p].grf_feature)) { + if (!HasBit(file->grf_features, _price_base_specs[p].grf_feature)) { /* The grf does not define any objects of the feature, * so it must be a difficulty setting. Apply it globally */ - DEBUG(grf, 3, "'%s' sets global price base multiplier %d", (*file)->filename, p); + DEBUG(grf, 3, "'%s' sets global price base multiplier %d", file->filename, p); SetPriceBaseMultiplier(p, price_base_multipliers[p]); price_base_multipliers[p] = 0; } else { - DEBUG(grf, 3, "'%s' sets local price base multiplier %d", (*file)->filename, p); + DEBUG(grf, 3, "'%s' sets local price base multiplier %d", file->filename, p); } } } @@ -9327,8 +9314,8 @@ extern void InitGRFTownGeneratorNames(); /** Finish loading NewGRFs and execute needed post-processing */ static void AfterLoadGRFs() { - for (StringIDMapping *it = _string_to_grf_mapping.Begin(); it != _string_to_grf_mapping.End(); it++) { - *it->target = MapGRFStringID(it->grfid, it->source); + for (StringIDMapping &it : _string_to_grf_mapping) { + *it.target = MapGRFStringID(it.grfid, it.source); } _string_to_grf_mapping.clear(); diff --git a/src/newgrf_commons.cpp b/src/newgrf_commons.cpp index e201ca7364..5626c6543e 100644 --- a/src/newgrf_commons.cpp +++ b/src/newgrf_commons.cpp @@ -683,7 +683,7 @@ uint32 NewGRFSpriteLayout::PrepareLayout(uint32 orig_offset, uint32 newgrf_groun * and apply the default sprite offsets (unless disabled). */ const TileLayoutRegisters *regs = this->registers; bool ground = true; - foreach_draw_tile_seq(result, result_seq.Begin()) { + foreach_draw_tile_seq(result, result_seq.data()) { TileLayoutFlags flags = TLF_NOTHING; if (regs != NULL) flags = regs->flags; @@ -737,7 +737,7 @@ void NewGRFSpriteLayout::ProcessRegisters(uint8 resolved_var10, uint32 resolved_ DrawTileSeqStruct *result; const TileLayoutRegisters *regs = this->registers; bool ground = true; - foreach_draw_tile_seq(result, result_seq.Begin()) { + foreach_draw_tile_seq(result, result_seq.data()) { TileLayoutFlags flags = TLF_NOTHING; if (regs != NULL) flags = regs->flags; diff --git a/src/newgrf_commons.h b/src/newgrf_commons.h index a5cedf429b..c7ca609fa9 100644 --- a/src/newgrf_commons.h +++ b/src/newgrf_commons.h @@ -164,7 +164,7 @@ struct NewGRFSpriteLayout : ZeroedMemoryAllocator, DrawTileSprites { */ const DrawTileSeqStruct *GetLayout(PalSpriteID *ground) const { - DrawTileSeqStruct *front = result_seq.Begin(); + DrawTileSeqStruct *front = result_seq.data(); *ground = front->image; return front + 1; } diff --git a/src/newgrf_config.cpp b/src/newgrf_config.cpp index 698084115d..e346a4a823 100644 --- a/src/newgrf_config.cpp +++ b/src/newgrf_config.cpp @@ -182,9 +182,9 @@ void GRFConfig::SetSuitablePalette() */ void GRFConfig::FinalizeParameterInfo() { - for (GRFParameterInfo **info = this->param_info.Begin(); info != this->param_info.End(); ++info) { - if (*info == NULL) continue; - (*info)->Finalize(); + for (GRFParameterInfo *info : this->param_info) { + if (info == NULL) continue; + info->Finalize(); } } diff --git a/src/newgrf_debug_gui.cpp b/src/newgrf_debug_gui.cpp index a081243572..f8745440c1 100644 --- a/src/newgrf_debug_gui.cpp +++ b/src/newgrf_debug_gui.cpp @@ -840,8 +840,8 @@ struct SpriteAlignerWindow : Window { /* Relative offset is new absolute offset - starting absolute offset. * Show 0, 0 as the relative offsets if entry is not in the map (meaning they have not been changed yet). */ - const SmallPair *key_offs_pair = this->offs_start_map.Find(this->current_sprite); - if (key_offs_pair != this->offs_start_map.End()) { + const auto key_offs_pair = this->offs_start_map.Find(this->current_sprite); + if (key_offs_pair != this->offs_start_map.end()) { SetDParam(0, spr->x_offs - key_offs_pair->second.first); SetDParam(1, spr->y_offs - key_offs_pair->second.second); } else { diff --git a/src/newgrf_engine.cpp b/src/newgrf_engine.cpp index 7a0bb04f3b..0c7e4314b8 100644 --- a/src/newgrf_engine.cpp +++ b/src/newgrf_engine.cpp @@ -1231,13 +1231,12 @@ void CommitVehicleListOrderChanges() FOR_ALL_ENGINES(e) { ordering.push_back(e->index); } - QSortT(ordering.Begin(), ordering.size(), EnginePreSort); + QSortT(ordering.data(), ordering.size(), EnginePreSort); /* Apply Insertion-Sort operations */ - const ListOrderChange *end = _list_order_changes.End(); - for (const ListOrderChange *it = _list_order_changes.Begin(); it != end; ++it) { - EngineID source = it->engine; - uint local_target = it->target; + for (const ListOrderChange &it : _list_order_changes) { + EngineID source = it.engine; + uint local_target = it.target; const EngineIDMapping *id_source = _engine_mngr.data() + source; if (id_source->internal_id == local_target) continue; @@ -1251,7 +1250,7 @@ void CommitVehicleListOrderChanges() assert(source_index >= 0 && target_index >= 0); assert(source_index != target_index); - EngineID *list = ordering.Begin(); + EngineID *list = ordering.data(); if (source_index < target_index) { --target_index; for (int i = source_index; i < target_index; ++i) list[i] = list[i + 1]; @@ -1263,10 +1262,10 @@ void CommitVehicleListOrderChanges() } /* Store final sort-order */ - const EngineID *idend = ordering.End(); uint index = 0; - for (const EngineID *it = ordering.Begin(); it != idend; ++it, ++index) { - Engine::Get(*it)->list_position = index; + for (const EngineID &eid : ordering) { + Engine::Get(eid)->list_position = index; + ++index; } /* Clear out the queue */ diff --git a/src/newgrf_text.cpp b/src/newgrf_text.cpp index b92b84355a..57f2ce5e4c 100644 --- a/src/newgrf_text.cpp +++ b/src/newgrf_text.cpp @@ -168,8 +168,8 @@ static byte _currentLangID = GRFLX_ENGLISH; ///< by default, english is used. int LanguageMap::GetMapping(int newgrf_id, bool gender) const { const SmallVector &map = gender ? this->gender_map : this->case_map; - for (const Mapping *m = map.Begin(); m != map.End(); m++) { - if (m->newgrf_id == newgrf_id) return m->openttd_id; + for (const Mapping &m : map) { + if (m.newgrf_id == newgrf_id) return m.openttd_id; } return -1; } @@ -183,8 +183,8 @@ int LanguageMap::GetMapping(int newgrf_id, bool gender) const int LanguageMap::GetReverseMapping(int openttd_id, bool gender) const { const SmallVector &map = gender ? this->gender_map : this->case_map; - for (const Mapping *m = map.Begin(); m != map.End(); m++) { - if (m->openttd_id == openttd_id) return m->newgrf_id; + for (const Mapping &m : map) { + if (m.openttd_id == openttd_id) return m.newgrf_id; } return -1; } @@ -194,8 +194,8 @@ struct UnmappedChoiceList : ZeroedMemoryAllocator { /** Clean everything up. */ ~UnmappedChoiceList() { - for (SmallPair *p = this->strings.Begin(); p < this->strings.End(); p++) { - free(p->second); + for (SmallPair p : this->strings) { + free(p.second); } } diff --git a/src/object_cmd.cpp b/src/object_cmd.cpp index 287a146f3d..26f0fc4e80 100644 --- a/src/object_cmd.cpp +++ b/src/object_cmd.cpp @@ -453,9 +453,8 @@ ClearedObjectArea *FindClearedObject(TileIndex tile) { TileArea ta = TileArea(tile, 1, 1); - const ClearedObjectArea *end = _cleared_object_areas.End(); - for (ClearedObjectArea *coa = _cleared_object_areas.Begin(); coa != end; coa++) { - if (coa->area.Intersects(ta)) return coa; + for (ClearedObjectArea &coa : _cleared_object_areas) { + if (coa.area.Intersects(ta)) return &coa; } return NULL; diff --git a/src/os/macosx/string_osx.cpp b/src/os/macosx/string_osx.cpp index 136542cc18..51cf50ea07 100644 --- a/src/os/macosx/string_osx.cpp +++ b/src/os/macosx/string_osx.cpp @@ -75,8 +75,8 @@ public: /* Extract font information for this run. */ CFRange chars = CTRunGetStringRange(run); - FontMap::const_iterator map = fontMapping.Begin(); - while (map < fontMapping.End() - 1 && map->first <= chars.location) map++; + auto map = fontMapping.begin(); + while (map < fontMapping.end() - 1 && map->first <= chars.location) map++; this->push_back(new CoreTextVisualRun(run, map->second, buff)); } @@ -137,8 +137,8 @@ static CTRunDelegateCallbacks _sprite_font_callback = { if (length == 0) return NULL; /* Can't layout our in-built sprite fonts. */ - for (FontMap::const_iterator i = fontMapping.Begin(); i != fontMapping.End(); i++) { - if (i->second->fc->IsBuiltInFont()) return NULL; + for (const auto &i : fontMapping) { + if (i.second->fc->IsBuiltInFont()) return NULL; } /* Make attributed string with embedded font information. */ @@ -152,31 +152,31 @@ static CTRunDelegateCallbacks _sprite_font_callback = { /* Apply font and colour ranges to our string. This is important to make sure * that we get proper glyph boundaries on style changes. */ int last = 0; - for (FontMap::const_iterator i = fontMapping.Begin(); i != fontMapping.End(); i++) { - if (i->first - last == 0) continue; + for (const auto &i : fontMapping) { + if (i.first - last == 0) continue; - if (_font_cache[i->second->fc->GetSize()] == NULL) { + if (_font_cache[i.second->fc->GetSize()] == NULL) { /* Cache font information. */ - CFStringRef font_name = CFStringCreateWithCString(kCFAllocatorDefault, i->second->fc->GetFontName(), kCFStringEncodingUTF8); - _font_cache[i->second->fc->GetSize()] = CTFontCreateWithName(font_name, i->second->fc->GetFontSize(), NULL); + CFStringRef font_name = CFStringCreateWithCString(kCFAllocatorDefault, i.second->fc->GetFontName(), kCFStringEncodingUTF8); + _font_cache[i.second->fc->GetSize()] = CTFontCreateWithName(font_name, i.second->fc->GetFontSize(), NULL); CFRelease(font_name); } - CFAttributedStringSetAttribute(str, CFRangeMake(last, i->first - last), kCTFontAttributeName, _font_cache[i->second->fc->GetSize()]); + CFAttributedStringSetAttribute(str, CFRangeMake(last, i.first - last), kCTFontAttributeName, _font_cache[i.second->fc->GetSize()]); - CGColorRef color = CGColorCreateGenericGray((uint8)i->second->colour / 255.0f, 1.0f); // We don't care about the real colours, just that they are different. - CFAttributedStringSetAttribute(str, CFRangeMake(last, i->first - last), kCTForegroundColorAttributeName, color); + CGColorRef color = CGColorCreateGenericGray((uint8)i.second->colour / 255.0f, 1.0f); // We don't care about the real colours, just that they are different. + CFAttributedStringSetAttribute(str, CFRangeMake(last, i.first - last), kCTForegroundColorAttributeName, color); CGColorRelease(color); /* Install a size callback for our special sprite glyphs. */ - for (ssize_t c = last; c < i->first; c++) { + for (ssize_t c = last; c < i.first; c++) { if (buff[c] >= SCC_SPRITE_START && buff[c] <= SCC_SPRITE_END) { - CTRunDelegateRef del = CTRunDelegateCreate(&_sprite_font_callback, (void *)(size_t)(buff[c] | (i->second->fc->GetSize() << 24))); + CTRunDelegateRef del = CTRunDelegateCreate(&_sprite_font_callback, (void *)(size_t)(buff[c] | (i.second->fc->GetSize() << 24))); CFAttributedStringSetAttribute(str, CFRangeMake(c, 1), kCTRunDelegateAttributeName, del); CFRelease(del); } } - last = i->first; + last = i.first; } CFAttributedStringEndEditing(str); @@ -243,8 +243,8 @@ CoreTextParagraphLayout::CoreTextVisualRun::CoreTextVisualRun(CTRunRef run, Font int CoreTextParagraphLayout::CoreTextLine::GetLeading() const { int leading = 0; - for (const CoreTextVisualRun * const *run = this->Begin(); run != this->End(); run++) { - leading = max(leading, (*run)->GetLeading()); + for (const CoreTextVisualRun * const &run : *this) { + leading = max(leading, run->GetLeading()); } return leading; @@ -259,8 +259,8 @@ int CoreTextParagraphLayout::CoreTextLine::GetWidth() const if (this->size() == 0) return 0; int total_width = 0; - for (const CoreTextVisualRun * const *run = this->Begin(); run != this->End(); run++) { - total_width += (*run)->GetAdvance(); + for (const CoreTextVisualRun * const &run : *this) { + total_width += run->GetAdvance(); } return total_width; diff --git a/src/os/windows/string_uniscribe.cpp b/src/os/windows/string_uniscribe.cpp index ec0e026394..a3fd35d0ad 100644 --- a/src/os/windows/string_uniscribe.cpp +++ b/src/os/windows/string_uniscribe.cpp @@ -282,8 +282,8 @@ static std::vector UniscribeItemizeString(UniscribeParagraphLayoutF if (length == 0) return NULL; /* Can't layout our in-built sprite fonts. */ - for (FontMap::const_iterator i = fontMapping.Begin(); i != fontMapping.End(); i++) { - if (i->second->fc->IsBuiltInFont()) return NULL; + for (auto const &pair : fontMapping) { + if (pair.second->fc->IsBuiltInFont()) return NULL; } /* Itemize text. */ @@ -296,12 +296,12 @@ static std::vector UniscribeItemizeString(UniscribeParagraphLayoutF int cur_pos = 0; std::vector::iterator cur_item = items.begin(); - for (FontMap::const_iterator i = fontMapping.Begin(); i != fontMapping.End(); i++) { - while (cur_pos < i->first && cur_item != items.end() - 1) { + for (auto const &i : fontMapping) { + while (cur_pos < i.first && cur_item != items.end() - 1) { /* Add a range that spans the intersection of the remaining item and font run. */ - int stop_pos = min(i->first, (cur_item + 1)->iCharPos); + int stop_pos = min(i.first, (cur_item + 1)->iCharPos); assert(stop_pos - cur_pos > 0); - ranges.push_back(UniscribeRun(cur_pos, stop_pos - cur_pos, i->second, cur_item->a)); + ranges.push_back(UniscribeRun(cur_pos, stop_pos - cur_pos, i.second, cur_item->a)); /* Shape the range. */ if (!UniscribeShapeRun(buff, ranges.back())) { @@ -448,8 +448,8 @@ static std::vector UniscribeItemizeString(UniscribeParagraphLayoutF int UniscribeParagraphLayout::UniscribeLine::GetLeading() const { int leading = 0; - for (const UniscribeVisualRun * const *run = this->Begin(); run != this->End(); run++) { - leading = max(leading, (*run)->GetLeading()); + for (const UniscribeVisualRun *run : *this) { + leading = max(leading, run->GetLeading()); } return leading; @@ -462,8 +462,8 @@ int UniscribeParagraphLayout::UniscribeLine::GetLeading() const int UniscribeParagraphLayout::UniscribeLine::GetWidth() const { int length = 0; - for (const UniscribeVisualRun * const *run = this->Begin(); run != this->End(); run++) { - length += (*run)->GetAdvance(); + for (const UniscribeVisualRun *run : *this) { + length += run->GetAdvance(); } return length; diff --git a/src/rail_cmd.cpp b/src/rail_cmd.cpp index c6548eefba..8e996bbe3c 100644 --- a/src/rail_cmd.cpp +++ b/src/rail_cmd.cpp @@ -1754,8 +1754,8 @@ CommandCost CmdConvertRail(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3 if (flags & DC_EXEC) { /* Railtype changed, update trains as when entering different track */ - for (Train **v = affected_trains.Begin(); v != affected_trains.End(); v++) { - (*v)->ConsistChanged(CCF_TRACK); + for (Train *v : affected_trains) { + v->ConsistChanged(CCF_TRACK); } } diff --git a/src/saveload/afterload.cpp b/src/saveload/afterload.cpp index 43a415c208..3efed69e45 100644 --- a/src/saveload/afterload.cpp +++ b/src/saveload/afterload.cpp @@ -2197,12 +2197,12 @@ bool AfterLoadGame() extern SmallVector _animated_tiles; - for (TileIndex *tile = _animated_tiles.Begin(); tile < _animated_tiles.End(); /* Nothing */) { + for (auto tile = _animated_tiles.begin(); tile < _animated_tiles.end(); /* Nothing */) { /* Remove if tile is not animated */ bool remove = _tile_type_procs[GetTileType(*tile)]->animate_tile_proc == NULL; /* and remove if duplicate */ - for (TileIndex *j = _animated_tiles.Begin(); !remove && j < tile; j++) { + for (auto j = _animated_tiles.begin(); !remove && j < tile; j++) { remove = *tile == *j; } @@ -2981,9 +2981,12 @@ bool AfterLoadGame() while (cur_skip > skip_frames[0]) { RoadVehicle *u = v; RoadVehicle *prev = NULL; - for (uint *it = skip_frames.Begin(); it != skip_frames.End(); ++it, prev = u, u = u->Next()) { + for (uint sf : skip_frames) { extern bool IndividualRoadVehicleController(RoadVehicle *v, const RoadVehicle *prev); - if (*it >= cur_skip) IndividualRoadVehicleController(u, prev); + if (sf >= cur_skip) IndividualRoadVehicleController(u, prev); + + prev = u; + u = u->Next(); } cur_skip--; } diff --git a/src/saveload/animated_tile_sl.cpp b/src/saveload/animated_tile_sl.cpp index 5b91852639..4d4ed69a96 100644 --- a/src/saveload/animated_tile_sl.cpp +++ b/src/saveload/animated_tile_sl.cpp @@ -25,8 +25,8 @@ extern SmallVector _animated_tiles; */ static void Save_ANIT() { - SlSetLength(_animated_tiles.size() * sizeof(*_animated_tiles.Begin())); - SlArray(_animated_tiles.Begin(), _animated_tiles.size(), SLE_UINT32); + SlSetLength(_animated_tiles.size() * sizeof(_animated_tiles.front())); + SlArray(_animated_tiles.data(), _animated_tiles.size(), SLE_UINT32); } /** @@ -47,10 +47,10 @@ static void Load_ANIT() return; } - uint count = (uint)SlGetFieldLength() / sizeof(*_animated_tiles.Begin()); + uint count = (uint)SlGetFieldLength() / sizeof(_animated_tiles.front()); _animated_tiles.clear(); _animated_tiles.resize(_animated_tiles.size() + count); - SlArray(_animated_tiles.Begin(), count, SLE_UINT32); + SlArray(_animated_tiles.data(), count, SLE_UINT32); } /** diff --git a/src/saveload/engine_sl.cpp b/src/saveload/engine_sl.cpp index 03a086a15d..891e307834 100644 --- a/src/saveload/engine_sl.cpp +++ b/src/saveload/engine_sl.cpp @@ -177,11 +177,11 @@ static const SaveLoad _engine_id_mapping_desc[] = { static void Save_EIDS() { - const EngineIDMapping *end = _engine_mngr.End(); uint index = 0; - for (EngineIDMapping *eid = _engine_mngr.Begin(); eid != end; eid++, index++) { + for (EngineIDMapping &eid : _engine_mngr) { SlSetArrayIndex(index); - SlObject(eid, _engine_id_mapping_desc); + SlObject(&eid, _engine_id_mapping_desc); + index++; } } diff --git a/src/saveload/waypoint_sl.cpp b/src/saveload/waypoint_sl.cpp index 9e5d163960..d7701c8af8 100644 --- a/src/saveload/waypoint_sl.cpp +++ b/src/saveload/waypoint_sl.cpp @@ -52,10 +52,10 @@ static void UpdateWaypointOrder(Order *o) { if (!o->IsType(OT_GOTO_WAYPOINT)) return; - for (OldWaypoint *wp = _old_waypoints.Begin(); wp != _old_waypoints.End(); wp++) { - if (wp->index != o->GetDestination()) continue; + for (OldWaypoint &wp : _old_waypoints) { + if (wp.index != o->GetDestination()) continue; - o->SetDestination((DestinationID)wp->new_index); + o->SetDestination((DestinationID)wp.new_index); return; } } @@ -71,25 +71,25 @@ void MoveWaypointsToBaseStations() * id which was stored in m4 is now saved as a grf/id reference in the * waypoint struct. */ if (IsSavegameVersionBefore(SLV_17)) { - for (OldWaypoint *wp = _old_waypoints.Begin(); wp != _old_waypoints.End(); wp++) { - if (wp->delete_ctr != 0) continue; // The waypoint was deleted + for (OldWaypoint &wp : _old_waypoints) { + if (wp.delete_ctr != 0) continue; // The waypoint was deleted /* Waypoint indices were not added to the map prior to this. */ - _m[wp->xy].m2 = (StationID)wp->index; + _m[wp.xy].m2 = (StationID)wp.index; - if (HasBit(_m[wp->xy].m3, 4)) { - wp->spec = StationClass::Get(STAT_CLASS_WAYP)->GetSpec(_m[wp->xy].m4 + 1); + if (HasBit(_m[wp.xy].m3, 4)) { + wp.spec = StationClass::Get(STAT_CLASS_WAYP)->GetSpec(_m[wp.xy].m4 + 1); } } } else { /* As of version 17, we recalculate the custom graphic ID of waypoints * from the GRF ID / station index. */ - for (OldWaypoint *wp = _old_waypoints.Begin(); wp != _old_waypoints.End(); wp++) { + for (OldWaypoint &wp : _old_waypoints) { StationClass* stclass = StationClass::Get(STAT_CLASS_WAYP); for (uint i = 0; i < stclass->GetSpecCount(); i++) { const StationSpec *statspec = stclass->GetSpec(i); - if (statspec != NULL && statspec->grf_prop.grffile->grfid == wp->grfid && statspec->grf_prop.local_id == wp->localidx) { - wp->spec = statspec; + if (statspec != NULL && statspec->grf_prop.grffile->grfid == wp.grfid && statspec->grf_prop.local_id == wp.localidx) { + wp.spec = statspec; break; } } @@ -99,19 +99,19 @@ void MoveWaypointsToBaseStations() if (!Waypoint::CanAllocateItem(_old_waypoints.size())) SlError(STR_ERROR_TOO_MANY_STATIONS_LOADING); /* All saveload conversions have been done. Create the new waypoints! */ - for (OldWaypoint *wp = _old_waypoints.Begin(); wp != _old_waypoints.End(); wp++) { - Waypoint *new_wp = new Waypoint(wp->xy); - new_wp->town = wp->town; - new_wp->town_cn = wp->town_cn; - new_wp->name = wp->name; + for (OldWaypoint &wp : _old_waypoints) { + Waypoint *new_wp = new Waypoint(wp.xy); + new_wp->town = wp.town; + new_wp->town_cn = wp.town_cn; + new_wp->name = wp.name; new_wp->delete_ctr = 0; // Just reset delete counter for once. - new_wp->build_date = wp->build_date; - new_wp->owner = wp->owner; + new_wp->build_date = wp.build_date; + new_wp->owner = wp.owner; new_wp->string_id = STR_SV_STNAME_WAYPOINT; - TileIndex t = wp->xy; - if (IsTileType(t, MP_RAILWAY) && GetRailTileType(t) == 2 /* RAIL_TILE_WAYPOINT */ && _m[t].m2 == wp->index) { + TileIndex t = wp.xy; + if (IsTileType(t, MP_RAILWAY) && GetRailTileType(t) == 2 /* RAIL_TILE_WAYPOINT */ && _m[t].m2 == wp.index) { /* The tile might've been reserved! */ bool reserved = !IsSavegameVersionBefore(SLV_100) && HasBit(_m[t].m5, 4); @@ -122,13 +122,13 @@ void MoveWaypointsToBaseStations() SetRailStationReservation(t, reserved); - if (wp->spec != NULL) { - SetCustomStationSpecIndex(t, AllocateSpecToStation(wp->spec, new_wp, true)); + if (wp.spec != NULL) { + SetCustomStationSpecIndex(t, AllocateSpecToStation(wp.spec, new_wp, true)); } new_wp->rect.BeforeAddTile(t, StationRect::ADD_FORCE); } - wp->new_index = new_wp->index; + wp.new_index = new_wp->index; } /* Update the orders of vehicles */ @@ -189,15 +189,15 @@ static void Load_WAYP() static void Ptrs_WAYP() { - for (OldWaypoint *wp = _old_waypoints.Begin(); wp != _old_waypoints.End(); wp++) { - SlObject(wp, _old_waypoint_desc); + for (OldWaypoint &wp : _old_waypoints) { + SlObject(&wp, _old_waypoint_desc); if (IsSavegameVersionBefore(SLV_12)) { - wp->town_cn = (wp->string_id & 0xC000) == 0xC000 ? (wp->string_id >> 8) & 0x3F : 0; - wp->town = ClosestTownFromTile(wp->xy, UINT_MAX); + wp.town_cn = (wp.string_id & 0xC000) == 0xC000 ? (wp.string_id >> 8) & 0x3F : 0; + wp.town = ClosestTownFromTile(wp.xy, UINT_MAX); } else if (IsSavegameVersionBefore(SLV_122)) { /* Only for versions 12 .. 122 */ - if (!Town::IsValidID(wp->town_index)) { + if (!Town::IsValidID(wp.town_index)) { /* Upon a corrupted waypoint we'll likely get here. The next step will be to * loop over all Ptrs procs to NULL the pointers. However, we don't know * whether we're in the NULL or "normal" Ptrs proc. So just clear the list @@ -206,10 +206,10 @@ static void Ptrs_WAYP() _old_waypoints.clear(); SlErrorCorrupt("Referencing invalid Town"); } - wp->town = Town::Get(wp->town_index); + wp.town = Town::Get(wp.town_index); } if (IsSavegameVersionBefore(SLV_84)) { - wp->name = CopyFromOldName(wp->string_id); + wp.name = CopyFromOldName(wp.string_id); } } } diff --git a/src/script/script_info.cpp b/src/script/script_info.cpp index b95c6e366d..47ff2ee5f9 100644 --- a/src/script/script_info.cpp +++ b/src/script/script_info.cpp @@ -26,8 +26,8 @@ ScriptInfo::~ScriptInfo() free((*it).name); free((*it).description); if (it->labels != NULL) { - for (LabelMapping::iterator it2 = (*it).labels->Begin(); it2 != (*it).labels->End(); it2++) { - free(it2->second); + for (auto &lbl_map : *(*it).labels) { + free(lbl_map.second); } delete it->labels; } diff --git a/src/script/squirrel_helper.hpp b/src/script/squirrel_helper.hpp index c362601eb2..775fe142ee 100644 --- a/src/script/squirrel_helper.hpp +++ b/src/script/squirrel_helper.hpp @@ -149,7 +149,7 @@ namespace SQConvert { Array *arr = (Array*)MallocT(sizeof(Array) + sizeof(int32) * data.size()); arr->size = data.size(); - memcpy(arr->array, data.Begin(), sizeof(int32) * data.size()); + memcpy(arr->array, data.data(), sizeof(int32) * data.size()); ptr->push_back(arr); return arr; diff --git a/src/settings.cpp b/src/settings.cpp index 2c9fc305e2..546b137a14 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -747,8 +747,8 @@ static void IniSaveSettingList(IniFile *ini, const char *grpname, StringList *li if (group == NULL || list == NULL) return; group->Clear(); - for (char **iter = list->Begin(); iter != list->End(); iter++) { - group->GetItem(*iter, true)->SetValue(""); + for (char *iter : *list) { + group->GetItem(iter, true)->SetValue(""); } } diff --git a/src/settings_gui.cpp b/src/settings_gui.cpp index da4989e858..cfed29d4d0 100644 --- a/src/settings_gui.cpp +++ b/src/settings_gui.cpp @@ -215,7 +215,7 @@ struct GameOptionsWindow : Window { if (i == CURRENCY_CUSTOM) continue; list->push_back(new DropDownListStringItem(*items, i, HasBit(disabled, i))); } - QSortT(list->Begin(), list->size(), DropDownListStringItem::NatSortFunc); + QSortT(list->data(), list->size(), DropDownListStringItem::NatSortFunc); /* Append custom currency at the end */ list->push_back(new DropDownListItem(-1, false)); // separator line @@ -253,7 +253,7 @@ struct GameOptionsWindow : Window { int result = _nb_orig_names + i; list->push_back(new DropDownListStringItem(_grf_names[i], result, enabled_item != result && enabled_item >= 0)); } - QSortT(list->Begin(), list->size(), DropDownListStringItem::NatSortFunc); + QSortT(list->data(), list->size(), DropDownListStringItem::NatSortFunc); int newgrf_size = list->size(); /* Insert newgrf_names at the top of the list */ @@ -266,7 +266,7 @@ struct GameOptionsWindow : Window { for (int i = 0; i < _nb_orig_names; i++) { list->push_back(new DropDownListStringItem(STR_GAME_OPTIONS_TOWN_NAME_ORIGINAL_ENGLISH + i, i, enabled_item != i && enabled_item >= 0)); } - QSortT(list->Begin() + newgrf_size, list->size() - newgrf_size, DropDownListStringItem::NatSortFunc); + QSortT(list->data() + newgrf_size, list->size() - newgrf_size, DropDownListStringItem::NatSortFunc); break; } @@ -286,7 +286,7 @@ struct GameOptionsWindow : Window { if (&_languages[i] == _current_language) *selected_index = i; list->push_back(new DropDownListStringItem(SPECSTR_LANGUAGE_START + i, i, false)); } - QSortT(list->Begin(), list->size(), DropDownListStringItem::NatSortFunc); + QSortT(list->data(), list->size(), DropDownListStringItem::NatSortFunc); break; } @@ -432,11 +432,11 @@ struct GameOptionsWindow : Window { DropDownList *list = this->BuildDropDownList(widget, &selected); if (list != NULL) { /* Find the biggest item for the default size. */ - for (const DropDownListItem * const *it = list->Begin(); it != list->End(); it++) { + for (const DropDownListItem * const ddli : *list) { Dimension string_dim; - int width = (*it)->Width(); + int width = ddli->Width(); string_dim.width = width + padding.width; - string_dim.height = (*it)->Height(width) + padding.height; + string_dim.height = ddli->Height(width) + padding.height; *size = maxdim(*size, string_dim); } delete list; diff --git a/src/settingsgen/settingsgen.cpp b/src/settingsgen/settingsgen.cpp index 1847bedff3..f52fe54268 100644 --- a/src/settingsgen/settingsgen.cpp +++ b/src/settingsgen/settingsgen.cpp @@ -136,8 +136,8 @@ public: */ void Write(FILE *out_fp) const { - for (const OutputBuffer *out_data = this->output_buffer.Begin(); out_data != this->output_buffer.End(); out_data++) { - out_data->Write(out_fp); + for (const OutputBuffer &out_data : output_buffer) { + out_data.Write(out_fp); } } diff --git a/src/station_cmd.cpp b/src/station_cmd.cpp index 6811290add..63e3384b04 100644 --- a/src/station_cmd.cpp +++ b/src/station_cmd.cpp @@ -1622,8 +1622,7 @@ CommandCost RemoveFromRailBaseStation(TileArea ta, SmallVector &affected if (quantity == 0) return error.Failed() ? error : CommandCost(STR_ERROR_THERE_IS_NO_STATION); - for (T **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) { - T *st = *stp; + for (T *st : affected_stations) { /* now we need to make the "spanned" area of the railway station smaller * if we deleted something at the edges. @@ -1667,8 +1666,7 @@ CommandCost CmdRemoveFromRailStation(TileIndex start, DoCommandFlag flags, uint3 if (ret.Failed()) return ret; /* Do all station specific functions here. */ - for (Station **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) { - Station *st = *stp; + for (Station *st : affected_stations) { if (st->train_station.tile == INVALID_TILE) SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS); st->MarkTilesDirty(false); diff --git a/src/story_gui.cpp b/src/story_gui.cpp index aed00358d0..5679bbdc6b 100644 --- a/src/story_gui.cpp +++ b/src/story_gui.cpp @@ -130,8 +130,7 @@ protected: int GetSelPageNum() const { int page_number = 0; - for (const StoryPage *const*iter = this->story_pages.Begin(); iter != this->story_pages.End(); iter++) { - const StoryPage *p = *iter; + for (const StoryPage *p : this->story_pages) { if (p->index == this->selected_page_id) { return page_number; } @@ -148,7 +147,7 @@ protected: /* Verify that the selected page exist. */ if (!_story_page_pool.IsValidID(this->selected_page_id)) return false; - return (*this->story_pages.Begin())->index == this->selected_page_id; + return this->story_pages.front()->index == this->selected_page_id; } /** @@ -160,7 +159,7 @@ protected: if (!_story_page_pool.IsValidID(this->selected_page_id)) return false; if (this->story_pages.size() <= 1) return true; - const StoryPage *last = *(this->story_pages.End() - 1); + const StoryPage *last = this->story_pages.back(); return last->index == this->selected_page_id; } @@ -195,8 +194,7 @@ protected: /* Find the last available page which is previous to the current selected page. */ const StoryPage *last_available; last_available = NULL; - for (const StoryPage *const*iter = this->story_pages.Begin(); iter != this->story_pages.End(); iter++) { - const StoryPage *p = *iter; + for (const StoryPage *p : this->story_pages) { if (p->index == this->selected_page_id) { if (last_available == NULL) return; // No previous page available. this->SetSelectedPage(last_available->index); @@ -214,12 +212,12 @@ protected: if (!_story_page_pool.IsValidID(this->selected_page_id)) return; /* Find selected page. */ - for (const StoryPage *const*iter = this->story_pages.Begin(); iter != this->story_pages.End(); iter++) { + for (auto iter = this->story_pages.begin(); iter != this->story_pages.end(); iter++) { const StoryPage *p = *iter; if (p->index == this->selected_page_id) { /* Select the page after selected page. */ iter++; - if (iter != this->story_pages.End()) { + if (iter != this->story_pages.end()) { this->SetSelectedPage((*iter)->index); } return; @@ -234,8 +232,7 @@ protected: { DropDownList *list = new DropDownList(); uint16 page_num = 1; - for (const StoryPage *const*iter = this->story_pages.Begin(); iter != this->story_pages.End(); iter++) { - const StoryPage *p = *iter; + for (const StoryPage *p : this->story_pages) { bool current_page = p->index == this->selected_page_id; DropDownListStringItem *item = NULL; if (p->title != NULL) { @@ -353,8 +350,7 @@ protected: uint height = GetHeadHeight(max_width); /* Body */ - for (const StoryPageElement **iter = this->story_page_elements.Begin(); iter != this->story_page_elements.End(); iter++) { - const StoryPageElement *pe = *iter; + for (const StoryPageElement *pe : this->story_page_elements) { height += element_vertical_dist; height += GetPageElementHeight(*pe, max_width); } @@ -532,8 +528,7 @@ public: y_offset = DrawStringMultiLine(0, right - x, y_offset, bottom - y, STR_STORY_BOOK_TITLE, TC_BLACK, SA_TOP | SA_HOR_CENTER); /* Page elements */ - for (const StoryPageElement *const*iter = this->story_page_elements.Begin(); iter != this->story_page_elements.End(); iter++) { - const StoryPageElement *const pe = *iter; + for (const StoryPageElement *const pe : this->story_page_elements) { y_offset += line_height; // margin to previous element switch (pe->type) { @@ -650,8 +645,7 @@ public: /* Detect if a page element was clicked. */ uint y = head_height; uint element_vertical_dist = FONT_HEIGHT_NORMAL; - for (const StoryPageElement *const*iter = this->story_page_elements.Begin(); iter != this->story_page_elements.End(); iter++) { - const StoryPageElement *const pe = *iter; + for (const StoryPageElement *const pe : this->story_page_elements) { y += element_vertical_dist; // margin row diff --git a/src/strgen/strgen_base.cpp b/src/strgen/strgen_base.cpp index 12d9938446..6c835782c8 100644 --- a/src/strgen/strgen_base.cpp +++ b/src/strgen/strgen_base.cpp @@ -1045,7 +1045,7 @@ void LanguageWriter::WriteLang(const StringData &data) if (cmdp != NULL) PutCommandString(&buffer, cmdp); this->WriteLength(buffer.size()); - this->Write(buffer.Begin(), buffer.size()); + this->Write(buffer.data(), buffer.size()); buffer.clear(); } } diff --git a/src/string.cpp b/src/string.cpp index c23202acbb..72254a877b 100644 --- a/src/string.cpp +++ b/src/string.cpp @@ -674,7 +674,7 @@ public: UText text = UTEXT_INITIALIZER; UErrorCode status = U_ZERO_ERROR; - utext_openUChars(&text, this->utf16_str.Begin(), this->utf16_str.size() - 1, &status); + utext_openUChars(&text, this->utf16_str.data(), this->utf16_str.size() - 1, &status); this->char_itr->setText(&text, status); this->word_itr->setText(&text, status); this->char_itr->first(); diff --git a/src/stringfilter.cpp b/src/stringfilter.cpp index e546a4186c..88eb5f28ad 100644 --- a/src/stringfilter.cpp +++ b/src/stringfilter.cpp @@ -91,9 +91,8 @@ void StringFilter::SetFilterTerm(const char *str) void StringFilter::ResetState() { this->word_matches = 0; - const WordState *end = this->word_index.End(); - for (WordState *it = this->word_index.Begin(); it != end; ++it) { - it->match = false; + for (WordState &ws : this->word_index) { + ws.match = false; } } @@ -110,11 +109,10 @@ void StringFilter::AddLine(const char *str) if (str == NULL) return; bool match_case = this->case_sensitive != NULL && *this->case_sensitive; - const WordState *end = this->word_index.End(); - for (WordState *it = this->word_index.Begin(); it != end; ++it) { - if (!it->match) { - if ((match_case ? strstr(str, it->start) : strcasestr(str, it->start)) != NULL) { - it->match = true; + for (WordState &ws : this->word_index) { + if (!ws.match) { + if ((match_case ? strstr(str, ws.start) : strcasestr(str, ws.start)) != NULL) { + ws.match = true; this->word_matches++; } } diff --git a/src/strings.cpp b/src/strings.cpp index c3f3061834..204c68c204 100644 --- a/src/strings.cpp +++ b/src/strings.cpp @@ -1876,8 +1876,8 @@ int CDECL StringIDSorter(const StringID *a, const StringID *b) */ const LanguageMetadata *GetLanguage(byte newgrflangid) { - for (const LanguageMetadata *lang = _languages.Begin(); lang != _languages.End(); lang++) { - if (newgrflangid == lang->newgrflangid) return lang; + for (const LanguageMetadata &lang : _languages) { + if (newgrflangid == lang.newgrflangid) return ⟨ } return NULL; @@ -1960,22 +1960,22 @@ void InitializeLanguagePacks() const LanguageMetadata *chosen_language = NULL; ///< Matching the language in the configuration file or the current locale const LanguageMetadata *language_fallback = NULL; ///< Using pt_PT for pt_BR locale when pt_BR is not available - const LanguageMetadata *en_GB_fallback = _languages.Begin(); ///< Fallback when no locale-matching language has been found + const LanguageMetadata *en_GB_fallback = _languages.data(); ///< Fallback when no locale-matching language has been found /* Find a proper language. */ - for (const LanguageMetadata *lng = _languages.Begin(); lng != _languages.End(); lng++) { + for (const LanguageMetadata &lng : _languages) { /* We are trying to find a default language. The priority is by * configuration file, local environment and last, if nothing found, * English. */ - const char *lang_file = strrchr(lng->file, PATHSEPCHAR) + 1; + const char *lang_file = strrchr(lng.file, PATHSEPCHAR) + 1; if (strcmp(lang_file, _config_language_file) == 0) { - chosen_language = lng; + chosen_language = &lng; break; } - if (strcmp (lng->isocode, "en_GB") == 0) en_GB_fallback = lng; - if (strncmp(lng->isocode, lang, 5) == 0) chosen_language = lng; - if (strncmp(lng->isocode, lang, 2) == 0) language_fallback = lng; + if (strcmp (lng.isocode, "en_GB") == 0) en_GB_fallback = &lng; + if (strncmp(lng.isocode, lang, 5) == 0) chosen_language = &lng; + if (strncmp(lng.isocode, lang, 2) == 0) language_fallback = &lng; } /* We haven't found the language in the config nor the one in the locale. diff --git a/src/subsidy.cpp b/src/subsidy.cpp index 8f823a1ab4..a61d6f1ce9 100644 --- a/src/subsidy.cpp +++ b/src/subsidy.cpp @@ -601,9 +601,9 @@ bool CheckSubsidised(CargoID cargo_type, CompanyID company, SourceType src_type, } break; case ST_TOWN: - for (const Town * const *tp = towns_near.Begin(); tp != towns_near.End(); tp++) { - if (s->dst == (*tp)->index) { - assert((*tp)->cache.part_of_subsidy & POS_DST); + for (const Town *tp : towns_near) { + if (s->dst == tp->index) { + assert(tp->cache.part_of_subsidy & POS_DST); subsidised = true; if (!s->IsAwarded()) s->AwardTo(company); } diff --git a/src/texteff.cpp b/src/texteff.cpp index c81d9a95d7..6827d980f0 100644 --- a/src/texteff.cpp +++ b/src/texteff.cpp @@ -89,20 +89,19 @@ void MoveAllTextEffects(uint delta_ms) uint count = texteffecttimer.CountElapsed(delta_ms); if (count == 0) return; - const TextEffect *end = _text_effects.End(); - for (TextEffect *te = _text_effects.Begin(); te != end; te++) { - if (te->string_id == INVALID_STRING_ID) continue; - if (te->mode != TE_RISING) continue; + for (TextEffect &te : _text_effects) { + if (te.string_id == INVALID_STRING_ID) continue; + if (te.mode != TE_RISING) continue; - if (te->duration < count) { - te->Reset(); + if (te.duration < count) { + te.Reset(); continue; } - te->MarkDirty(ZOOM_LVL_OUT_8X); - te->duration -= count; - te->top -= count * ZOOM_LVL_BASE; - te->MarkDirty(ZOOM_LVL_OUT_8X); + te.MarkDirty(ZOOM_LVL_OUT_8X); + te.duration -= count; + te.top -= count * ZOOM_LVL_BASE; + te.MarkDirty(ZOOM_LVL_OUT_8X); } } @@ -117,11 +116,10 @@ void DrawTextEffects(DrawPixelInfo *dpi) /* Don't draw the text effects when zoomed out a lot */ if (dpi->zoom > ZOOM_LVL_OUT_8X) return; - const TextEffect *end = _text_effects.End(); - for (TextEffect *te = _text_effects.Begin(); te != end; te++) { - if (te->string_id == INVALID_STRING_ID) continue; - if (te->mode == TE_RISING || (_settings_client.gui.loading_indicators && !IsTransparencySet(TO_LOADING))) { - ViewportAddString(dpi, ZOOM_LVL_OUT_8X, te, te->string_id, te->string_id - 1, STR_NULL, te->params_1, te->params_2); + for (TextEffect &te : _text_effects) { + if (te.string_id == INVALID_STRING_ID) continue; + if (te.mode == TE_RISING || (_settings_client.gui.loading_indicators && !IsTransparencySet(TO_LOADING))) { + ViewportAddString(dpi, ZOOM_LVL_OUT_8X, &te, te.string_id, te.string_id - 1, STR_NULL, te.params_1, te.params_2); } } } diff --git a/src/timetable_cmd.cpp b/src/timetable_cmd.cpp index fcc8493e2b..7e718c717d 100644 --- a/src/timetable_cmd.cpp +++ b/src/timetable_cmd.cpp @@ -295,13 +295,12 @@ CommandCost CmdSetTimetableStart(TileIndex tile, DoCommandFlag flags, uint32 p1, int num_vehs = vehs.size(); if (num_vehs >= 2) { - QSortT(vehs.Begin(), vehs.size(), &VehicleTimetableSorter); + QSortT(vehs.data(), vehs.size(), &VehicleTimetableSorter); } int idx = vehs.begin() - std::find(vehs.begin(), vehs.end(), v); - for (Vehicle **viter = vehs.Begin(); viter != vehs.End(); viter++) { - Vehicle *w = *viter; + for (Vehicle *w : vehs) { w->lateness_counter = 0; ClrBit(w->vehicle_flags, VF_TIMETABLE_STARTED); diff --git a/src/train_cmd.cpp b/src/train_cmd.cpp index 0d4df42f45..6ce1131844 100644 --- a/src/train_cmd.cpp +++ b/src/train_cmd.cpp @@ -837,8 +837,7 @@ static void RestoreTrainBackup(TrainList &list) Train *prev = NULL; /* Iterate over the list and rebuild it. */ - for (Train **iter = list.Begin(); iter != list.End(); iter++) { - Train *t = *iter; + for (Train *t : list) { if (prev != NULL) { prev->SetNext(t); } else if (t->Previous() != NULL) { diff --git a/src/train_gui.cpp b/src/train_gui.cpp index 3036096c89..427d45dea4 100644 --- a/src/train_gui.cpp +++ b/src/train_gui.cpp @@ -278,10 +278,10 @@ static void GetCargoSummaryOfArticulatedVehicle(const Train *v, CargoSummary *su new_item.subtype = GetCargoSubtypeText(v); if (new_item.cargo == INVALID_CARGO && new_item.subtype == STR_EMPTY) continue; - CargoSummaryItem *item = &*std::find(summary->begin(), summary->end(), new_item); - if (item == summary->End()) { - /*C++17: item = &*/ summary->emplace_back(); - item = &summary->back(); + auto item = std::find(summary->begin(), summary->end(), new_item); + if (item == summary->end()) { + summary->emplace_back(); + item = summary->end() - 1; item->cargo = new_item.cargo; item->subtype = new_item.subtype; item->capacity = 0; diff --git a/src/tunnelbridge_cmd.cpp b/src/tunnelbridge_cmd.cpp index 764551d81f..79011a3bd5 100644 --- a/src/tunnelbridge_cmd.cpp +++ b/src/tunnelbridge_cmd.cpp @@ -698,8 +698,9 @@ CommandCost CmdBuildTunnel(TileIndex start_tile, DoCommandFlag flags, uint32 p1, * Deliberately clear the coa pointer to avoid leaving dangling pointers which could * inadvertently be dereferenced. */ - assert(coa >= _cleared_object_areas.Begin() && coa < _cleared_object_areas.End()); - size_t coa_index = coa - _cleared_object_areas.Begin(); + ClearedObjectArea *begin = _cleared_object_areas.data(); + assert(coa >= begin && coa < begin + _cleared_object_areas.size()); + size_t coa_index = coa - begin; assert(coa_index < UINT_MAX); // more than 2**32 cleared areas would be a bug in itself coa = NULL; diff --git a/src/vehicle.cpp b/src/vehicle.cpp index 267c204913..9f15d9be05 100644 --- a/src/vehicle.cpp +++ b/src/vehicle.cpp @@ -1028,15 +1028,15 @@ void CallVehicleTicks() } Backup cur_company(_current_company, FILE_LINE); - for (AutoreplaceMap::iterator it = _vehicles_to_autoreplace.Begin(); it != _vehicles_to_autoreplace.End(); it++) { - v = it->first; + for (auto &it : _vehicles_to_autoreplace) { + v = it.first; /* Autoreplace needs the current company set as the vehicle owner */ cur_company.Change(v->owner); /* Start vehicle if we stopped them in VehicleEnteredDepotThisTick() * We need to stop them between VehicleEnteredDepotThisTick() and here or we risk that * they are already leaving the depot again before being replaced. */ - if (it->second) v->vehstatus &= ~VS_STOPPED; + if (it.second) v->vehstatus &= ~VS_STOPPED; /* Store the position of the effect as the vehicle pointer will become invalid later */ int x = v->x_pos; diff --git a/src/vehicle_cmd.cpp b/src/vehicle_cmd.cpp index 8e578cd68d..872c9458ca 100644 --- a/src/vehicle_cmd.cpp +++ b/src/vehicle_cmd.cpp @@ -422,17 +422,17 @@ static CommandCost RefitVehicle(Vehicle *v, bool only_this, uint8 num_vehicles, if (flags & DC_EXEC) { /* Store the result */ - for (RefitResult *result = refit_result.Begin(); result != refit_result.End(); result++) { - Vehicle *u = result->v; - u->refit_cap = (u->cargo_type == new_cid) ? min(result->capacity, u->refit_cap) : 0; + for (RefitResult &result : refit_result) { + Vehicle *u = result.v; + u->refit_cap = (u->cargo_type == new_cid) ? min(result.capacity, u->refit_cap) : 0; if (u->cargo.TotalCount() > u->refit_cap) u->cargo.Truncate(u->cargo.TotalCount() - u->refit_cap); u->cargo_type = new_cid; - u->cargo_cap = result->capacity; - u->cargo_subtype = result->subtype; + u->cargo_cap = result.capacity; + u->cargo_subtype = result.subtype; if (u->type == VEH_AIRCRAFT) { Vehicle *w = u->Next(); - w->refit_cap = min(w->refit_cap, result->mail_capacity); - w->cargo_cap = result->mail_capacity; + w->refit_cap = min(w->refit_cap, result.mail_capacity); + w->cargo_cap = result.mail_capacity; if (w->cargo.TotalCount() > w->refit_cap) w->cargo.Truncate(w->cargo.TotalCount() - w->refit_cap); } } diff --git a/src/vehicle_gui.cpp b/src/vehicle_gui.cpp index 82403a2d1b..9b6c68a36e 100644 --- a/src/vehicle_gui.cpp +++ b/src/vehicle_gui.cpp @@ -106,8 +106,8 @@ const StringID BaseVehicleListWindow::vehicle_depot_name[] = { uint GetUnitNumberDigits(VehicleList &vehicles) { uint unitnumber = 0; - for (const Vehicle **v = vehicles.Begin(); v != vehicles.End(); v++) { - unitnumber = max(unitnumber, (*v)->unitnumber); + for (const Vehicle *v : vehicles) { + unitnumber = max(unitnumber, v->unitnumber); } if (unitnumber >= 10000) return 5; @@ -194,7 +194,7 @@ void BaseVehicleListWindow::SortVehicleList() void DepotSortList(VehicleList *list) { if (list->size() < 2) return; - QSortT(list->Begin(), list->size(), &VehicleNumberSorter); + QSortT(list->data(), list->size(), &VehicleNumberSorter); } /** draw the vehicle profit button in the vehicle list window. */ diff --git a/src/viewport.cpp b/src/viewport.cpp index 929616ba52..892e94d603 100644 --- a/src/viewport.cpp +++ b/src/viewport.cpp @@ -628,8 +628,8 @@ static void AddCombinedSprite(SpriteID image, PaletteID pal, int x, int y, int z pt.y + spr->y_offs + spr->height <= _vd.dpi.top) return; - const ParentSpriteToDraw *pstd = _vd.parent_sprites_to_draw.End() - 1; - AddChildSpriteScreen(image, pal, pt.x - pstd->left, pt.y - pstd->top, false, sub, false); + const ParentSpriteToDraw &pstd = _vd.parent_sprites_to_draw.back(); + AddChildSpriteScreen(image, pal, pt.x - pstd.left, pt.y - pstd.top, false, sub, false); } /** @@ -1393,9 +1393,8 @@ void ViewportSign::MarkDirty(ZoomLevel maxzoom) const static void ViewportDrawTileSprites(const TileSpriteToDrawVector *tstdv) { - const TileSpriteToDraw *tsend = tstdv->End(); - for (const TileSpriteToDraw *ts = tstdv->Begin(); ts != tsend; ++ts) { - DrawSpriteViewport(ts->image, ts->pal, ts->x, ts->y, ts->sub); + for (const TileSpriteToDraw &ts : *tstdv) { + DrawSpriteViewport(ts.image, ts.pal, ts.x, ts.y, ts.sub); } } @@ -1408,8 +1407,8 @@ static bool ViewportSortParentSpritesChecker() /** Sort parent sprites pointer array */ static void ViewportSortParentSprites(ParentSpriteToSortVector *psdv) { - ParentSpriteToDraw **psdvend = psdv->End(); - ParentSpriteToDraw **psd = psdv->Begin(); + auto psdvend = psdv->end(); + auto psd = psdv->begin(); while (psd != psdvend) { ParentSpriteToDraw *ps = *psd; @@ -1420,7 +1419,7 @@ static void ViewportSortParentSprites(ParentSpriteToSortVector *psdv) ps->comparison_done = true; - for (ParentSpriteToDraw **psd2 = psd + 1; psd2 != psdvend; psd2++) { + for (auto psd2 = psd + 1; psd2 != psdvend; psd2++) { ParentSpriteToDraw *ps2 = *psd2; if (ps2->comparison_done) continue; @@ -1455,7 +1454,7 @@ static void ViewportSortParentSprites(ParentSpriteToSortVector *psdv) /* Move ps2 in front of ps */ ParentSpriteToDraw *temp = ps2; - for (ParentSpriteToDraw **psd3 = psd2; psd3 > psd; psd3--) { + for (auto psd3 = psd2; psd3 > psd; psd3--) { *psd3 = *(psd3 - 1); } *psd = temp; @@ -1465,9 +1464,7 @@ static void ViewportSortParentSprites(ParentSpriteToSortVector *psdv) static void ViewportDrawParentSprites(const ParentSpriteToSortVector *psd, const ChildScreenSpriteToDrawVector *csstdv) { - const ParentSpriteToDraw * const *psd_end = psd->End(); - for (const ParentSpriteToDraw * const *it = psd->Begin(); it != psd_end; it++) { - const ParentSpriteToDraw *ps = *it; + for (const ParentSpriteToDraw *ps : *psd) { if (ps->image != SPR_EMPTY_BOUNDING_BOX) DrawSpriteViewport(ps->image, ps->pal, ps->x, ps->y, ps->sub); int child_idx = ps->first_child; @@ -1485,9 +1482,7 @@ static void ViewportDrawParentSprites(const ParentSpriteToSortVector *psd, const */ static void ViewportDrawBoundingBoxes(const ParentSpriteToSortVector *psd) { - const ParentSpriteToDraw * const *psd_end = psd->End(); - for (const ParentSpriteToDraw * const *it = psd->Begin(); it != psd_end; it++) { - const ParentSpriteToDraw *ps = *it; + for (const ParentSpriteToDraw *ps : *psd) { Point pt1 = RemapCoords(ps->xmax + 1, ps->ymax + 1, ps->zmax + 1); // top front corner Point pt2 = RemapCoords(ps->xmin , ps->ymax + 1, ps->zmax + 1); // top left corner Point pt3 = RemapCoords(ps->xmax + 1, ps->ymin , ps->zmax + 1); // top right corner @@ -1524,38 +1519,37 @@ static void ViewportDrawDirtyBlocks() static void ViewportDrawStrings(ZoomLevel zoom, const StringSpriteToDrawVector *sstdv) { - const StringSpriteToDraw *ssend = sstdv->End(); - for (const StringSpriteToDraw *ss = sstdv->Begin(); ss != ssend; ++ss) { + for (const StringSpriteToDraw &ss : *sstdv) { TextColour colour = TC_BLACK; - bool small = HasBit(ss->width, 15); - int w = GB(ss->width, 0, 15); - int x = UnScaleByZoom(ss->x, zoom); - int y = UnScaleByZoom(ss->y, zoom); + bool small = HasBit(ss.width, 15); + int w = GB(ss.width, 0, 15); + int x = UnScaleByZoom(ss.x, zoom); + int y = UnScaleByZoom(ss.y, zoom); int h = VPSM_TOP + (small ? FONT_HEIGHT_SMALL : FONT_HEIGHT_NORMAL) + VPSM_BOTTOM; - SetDParam(0, ss->params[0]); - SetDParam(1, ss->params[1]); + SetDParam(0, ss.params[0]); + SetDParam(1, ss.params[1]); - if (ss->colour != INVALID_COLOUR) { + if (ss.colour != INVALID_COLOUR) { /* Do not draw signs nor station names if they are set invisible */ - if (IsInvisibilitySet(TO_SIGNS) && ss->string != STR_WHITE_SIGN) continue; + if (IsInvisibilitySet(TO_SIGNS) && ss.string != STR_WHITE_SIGN) continue; - if (IsTransparencySet(TO_SIGNS) && ss->string != STR_WHITE_SIGN) { + if (IsTransparencySet(TO_SIGNS) && ss.string != STR_WHITE_SIGN) { /* Don't draw the rectangle. * Real colours need the TC_IS_PALETTE_COLOUR flag. * Otherwise colours from _string_colourmap are assumed. */ - colour = (TextColour)_colour_gradient[ss->colour][6] | TC_IS_PALETTE_COLOUR; + colour = (TextColour)_colour_gradient[ss.colour][6] | TC_IS_PALETTE_COLOUR; } else { /* Draw the rectangle if 'transparent station signs' is off, * or if we are drawing a general text sign (STR_WHITE_SIGN). */ DrawFrameRect( - x, y, x + w, y + h, ss->colour, + x, y, x + w, y + h, ss.colour, IsTransparencySet(TO_SIGNS) ? FR_TRANSPARENT : FR_NONE ); } } - DrawString(x + VPSM_LEFT, x + w - 1 - VPSM_RIGHT, y + VPSM_TOP, ss->string, colour, SA_HOR_CENTER); + DrawString(x + VPSM_LEFT, x + w - 1 - VPSM_RIGHT, y + VPSM_TOP, ss.string, colour, SA_HOR_CENTER); } } @@ -1590,9 +1584,8 @@ void ViewportDoDraw(const ViewPort *vp, int left, int top, int right, int bottom if (_vd.tile_sprites_to_draw.size() != 0) ViewportDrawTileSprites(&_vd.tile_sprites_to_draw); - ParentSpriteToDraw *psd_end = _vd.parent_sprites_to_draw.End(); - for (ParentSpriteToDraw *it = _vd.parent_sprites_to_draw.Begin(); it != psd_end; it++) { - _vd.parent_sprites_to_sort.push_back(it); + for (auto &psd : _vd.parent_sprites_to_draw) { + _vd.parent_sprites_to_sort.push_back(&psd); } _vp_sprite_sorter(&_vd.parent_sprites_to_sort); diff --git a/src/viewport_sprite_sorter_sse4.cpp b/src/viewport_sprite_sorter_sse4.cpp index fb78c51c86..212ff12e68 100644 --- a/src/viewport_sprite_sorter_sse4.cpp +++ b/src/viewport_sprite_sorter_sse4.cpp @@ -29,8 +29,8 @@ void ViewportSortParentSpritesSSE41(ParentSpriteToSortVector *psdv) { const __m128i mask_ptest = _mm_setr_epi8(-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0); - ParentSpriteToDraw ** const psdvend = psdv->End(); - ParentSpriteToDraw **psd = psdv->Begin(); + auto const psdvend = psdv->end(); + auto psd = psdv->begin(); while (psd != psdvend) { ParentSpriteToDraw * const ps = *psd; @@ -41,7 +41,7 @@ void ViewportSortParentSpritesSSE41(ParentSpriteToSortVector *psdv) ps->comparison_done = true; - for (ParentSpriteToDraw **psd2 = psd + 1; psd2 != psdvend; psd2++) { + for (auto psd2 = psd + 1; psd2 != psdvend; psd2++) { ParentSpriteToDraw * const ps2 = *psd2; if (ps2->comparison_done) continue; @@ -85,7 +85,7 @@ void ViewportSortParentSpritesSSE41(ParentSpriteToSortVector *psdv) /* Move ps2 in front of ps */ ParentSpriteToDraw * const temp = ps2; - for (ParentSpriteToDraw **psd3 = psd2; psd3 > psd; psd3--) { + for (auto psd3 = psd2; psd3 > psd; psd3--) { *psd3 = *(psd3 - 1); } *psd = temp; diff --git a/src/widgets/dropdown.cpp b/src/widgets/dropdown.cpp index 33d59effc4..7c59cca7a5 100644 --- a/src/widgets/dropdown.cpp +++ b/src/widgets/dropdown.cpp @@ -174,8 +174,7 @@ struct DropdownWindow : Window { /* Total length of list */ int list_height = 0; - for (const DropDownListItem * const *it = list->Begin(); it != list->End(); ++it) { - const DropDownListItem *item = *it; + for (const DropDownListItem *item : *list) { list_height += item->Height(items_width); } @@ -230,13 +229,10 @@ struct DropdownWindow : Window { int width = nwi->current_x - 4; int pos = this->vscroll->GetPosition(); - const DropDownList *list = this->list; - - for (const DropDownListItem * const *it = list->Begin(); it != list->End(); ++it) { + for (const DropDownListItem *item : *this->list) { /* Skip items that are scrolled up */ if (--pos >= 0) continue; - const DropDownListItem *item = *it; int item_height = item->Height(width); if (y < item_height) { @@ -259,8 +255,7 @@ struct DropdownWindow : Window { int y = r.top + 2; int pos = this->vscroll->GetPosition(); - for (const DropDownListItem * const *it = this->list->Begin(); it != this->list->End(); ++it) { - const DropDownListItem *item = *it; + for (const DropDownListItem *item : *this->list) { int item_height = item->Height(r.right - r.left + 1); /* Skip items that are scrolled up */ @@ -389,8 +384,7 @@ void ShowDropDownListAt(Window *w, const DropDownList *list, int selected, int b /* Total height of list */ uint height = 0; - for (const DropDownListItem * const *it = list->Begin(); it != list->End(); ++it) { - const DropDownListItem *item = *it; + for (const DropDownListItem *item : *list) { height += item->Height(width); if (auto_width) max_item_width = max(max_item_width, item->Width() + 5); } diff --git a/src/window.cpp b/src/window.cpp index a8d1ce75e2..9366b92eb8 100644 --- a/src/window.cpp +++ b/src/window.cpp @@ -144,9 +144,9 @@ void WindowDesc::LoadFromConfig() { IniFile *ini = new IniFile(); ini->LoadFromDisk(_windows_file, NO_DIRECTORY); - for (WindowDesc **it = _window_descs->Begin(); it != _window_descs->End(); ++it) { - if ((*it)->ini_key == NULL) continue; - IniLoadWindowSettings(ini, (*it)->ini_key, *it); + for (WindowDesc *wd : *_window_descs) { + if (wd->ini_key == NULL) continue; + IniLoadWindowSettings(ini, wd->ini_key, wd); } delete ini; } @@ -166,13 +166,13 @@ static int CDECL DescSorter(WindowDesc * const *a, WindowDesc * const *b) void WindowDesc::SaveToConfig() { /* Sort the stuff to get a nice ini file on first write */ - QSortT(_window_descs->Begin(), _window_descs->size(), DescSorter); + QSortT(_window_descs->data(), _window_descs->size(), DescSorter); IniFile *ini = new IniFile(); ini->LoadFromDisk(_windows_file, NO_DIRECTORY); - for (WindowDesc **it = _window_descs->Begin(); it != _window_descs->End(); ++it) { - if ((*it)->ini_key == NULL) continue; - IniSaveWindowSettings(ini, (*it)->ini_key, *it); + for (WindowDesc *wd : *_window_descs) { + if (wd->ini_key == NULL) continue; + IniSaveWindowSettings(ini, wd->ini_key, wd); } ini->SaveToDisk(_windows_file); delete ini; @@ -330,8 +330,8 @@ Scrollbar *Window::GetScrollbar(uint widnum) */ const QueryString *Window::GetQueryString(uint widnum) const { - const SmallMap::Pair *query = this->querystrings.Find(widnum); - return query != this->querystrings.End() ? query->second : NULL; + auto query = this->querystrings.Find(widnum); + return query != this->querystrings.end() ? query->second : NULL; } /** @@ -1944,8 +1944,8 @@ static void DecreaseWindowCounters() } /* Handle editboxes */ - for (SmallMap::Pair *it = w->querystrings.Begin(); it != w->querystrings.End(); ++it) { - it->second->HandleEditBox(w, it->first); + for (SmallMap::Pair &pair : w->querystrings) { + pair.second->HandleEditBox(w, pair.first); } w->OnMouseLoop(); @@ -3252,8 +3252,9 @@ void Window::InvalidateData(int data, bool gui_scope) */ void Window::ProcessScheduledInvalidations() { - for (int *data = this->scheduled_invalidation_data.Begin(); this->window_class != WC_INVALID && data != this->scheduled_invalidation_data.End(); data++) { - this->OnInvalidateData(*data, true); + for (int data : this->scheduled_invalidation_data) { + if (this->window_class == WC_INVALID) break; + this->OnInvalidateData(data, true); } this->scheduled_invalidation_data.clear(); }