Codechange: Replaced SmallVector::[Begin|End]() with std alternatives

pull/82/head
Henry Wilson 5 years ago committed by PeterN
parent 297fd3dda3
commit ab711e6942

@ -53,8 +53,8 @@ void AnimateAnimatedTiles()
{ {
PerformanceAccumulator framerate(PFE_GL_LANDSCAPE); PerformanceAccumulator framerate(PFE_GL_LANDSCAPE);
const TileIndex *ti = _animated_tiles.Begin(); const TileIndex *ti = _animated_tiles.data();
while (ti < _animated_tiles.End()) { while (ti < _animated_tiles.data() + _animated_tiles.size()) {
const TileIndex curr = *ti; const TileIndex curr = *ti;
AnimateTile(curr); AnimateTile(curr);
/* During the AnimateTile call, DeleteAnimatedTile could have been called, /* During the AnimateTile call, DeleteAnimatedTile could have been called,

@ -183,8 +183,8 @@ class ReplaceVehicleWindow : public Window {
this->vscroll[1]->SetCount(this->engines[1].size()); this->vscroll[1]->SetCount(this->engines[1].size());
if (this->reset_sel_engine && this->sel_engine[1] != INVALID_ENGINE) { if (this->reset_sel_engine && this->sel_engine[1] != INVALID_ENGINE) {
int position = 0; int position = 0;
for (EngineID *it = this->engines[1].Begin(); it != this->engines[1].End(); ++it) { for (EngineID &eid : this->engines[1]) {
if (*it == this->sel_engine[1]) break; if (eid == this->sel_engine[1]) break;
++position; ++position;
} }
this->vscroll[1]->ScrollTowards(position); this->vscroll[1]->ScrollTowards(position);

@ -76,9 +76,9 @@ struct BaseSet {
{ {
free(this->name); free(this->name);
for (TranslatedStrings::iterator iter = this->description.Begin(); iter != this->description.End(); iter++) { for (auto &pair : this->description) {
free(iter->first); free(pair.first);
free(iter->second); free(pair.second);
} }
for (uint i = 0; i < NUM_FILES; i++) { for (uint i = 0; i < NUM_FILES; i++) {
@ -122,16 +122,16 @@ struct BaseSet {
{ {
if (isocode != NULL) { if (isocode != NULL) {
/* First the full ISO code */ /* First the full ISO code */
for (TranslatedStrings::const_iterator iter = this->description.Begin(); iter != this->description.End(); iter++) { for (const auto &pair : this->description) {
if (strcmp(iter->first, isocode) == 0) return iter->second; if (strcmp(pair.first, isocode) == 0) return pair.second;
} }
/* Then the first two characters */ /* Then the first two characters */
for (TranslatedStrings::const_iterator iter = this->description.Begin(); iter != this->description.End(); iter++) { for (const auto &pair : this->description) {
if (strncmp(iter->first, isocode, 2) == 0) return iter->second; if (strncmp(pair.first, isocode, 2) == 0) return pair.second;
} }
} }
/* Then fall back */ /* Then fall back */
return this->description.Begin()->second; return this->description.front().second;
} }
/** /**

@ -640,11 +640,11 @@ private:
void AddChildren(GUIGroupList *source, GroupID parent, int indent) void AddChildren(GUIGroupList *source, GroupID parent, int indent)
{ {
for (const Group **g = source->Begin(); g != source->End(); g++) { for (const Group *g : *source) {
if ((*g)->parent != parent) continue; if (g->parent != parent) continue;
this->groups.push_back(*g); this->groups.push_back(g);
this->indents.push_back(indent); this->indents.push_back(indent);
AddChildren(source, (*g)->index, indent + 1); AddChildren(source, g->index, indent + 1);
} }
} }

@ -585,8 +585,8 @@ DEF_CONSOLE_CMD(ConBanList)
IConsolePrint(CC_DEFAULT, "Banlist: "); IConsolePrint(CC_DEFAULT, "Banlist: ");
uint i = 1; uint i = 1;
for (char **iter = _network_ban_list.Begin(); iter != _network_ban_list.End(); iter++, i++) { for (char *entry : _network_ban_list) {
IConsolePrintF(CC_DEFAULT, " %d) %s", i, *iter); IConsolePrintF(CC_DEFAULT, " %d) %s", i, entry);
} }
return true; return true;

@ -31,10 +31,7 @@
*/ */
/* static */ void PoolBase::Clean(PoolType pt) /* static */ void PoolBase::Clean(PoolType pt)
{ {
PoolVector *pools = PoolBase::GetPools(); for (PoolBase *pool : *PoolBase::GetPools()) {
PoolBase **end = pools->End();
for (PoolBase **ppool = pools->Begin(); ppool != end; ppool++) {
PoolBase *pool = *ppool;
if (pool->type & pt) pool->CleanPool(); if (pool->type & pt) pool->CleanPool();
} }
} }

@ -55,12 +55,13 @@ struct SmallMap : SmallVector<SmallPair<T, U>, S> {
* @param key key to find * @param key key to find
* @return &Pair(key, data) if found, this->End() if not * @return &Pair(key, data) if found, this->End() if not
*/ */
inline const Pair *Find(const T &key) const inline typename std::vector<Pair>::const_iterator Find(const T &key) const
{ {
for (uint i = 0; i < std::vector<Pair>::size(); i++) { typename std::vector<Pair>::const_iterator it;
if (key == std::vector<Pair>::operator[](i).first) return &std::vector<Pair>::operator[](i); for (it = std::vector<Pair>::begin(); it != std::vector<Pair>::end(); it++) {
if (key == it->first) return it;
} }
return this->End(); return it;
} }
/** /**
@ -114,7 +115,7 @@ struct SmallMap : SmallVector<SmallPair<T, U>, S> {
*/ */
inline void Erase(Pair *pair) inline void Erase(Pair *pair)
{ {
assert(pair >= this->Begin() && pair < this->End()); assert(pair >= std::vector<Pair>::data() && pair < this->End());
auto distance = pair - std::vector<Pair>::data(); auto distance = pair - std::vector<Pair>::data();
std::vector<Pair>::erase(std::vector<Pair>::begin() + distance); std::vector<Pair>::erase(std::vector<Pair>::begin() + distance);
} }
@ -166,7 +167,7 @@ struct SmallMap : SmallVector<SmallPair<T, U>, S> {
inline void SortByKey() inline void SortByKey()
{ {
QSortT(this->Begin(), std::vector<Pair>::size(), KeySorter); QSortT(std::vector<Pair>::data(), std::vector<Pair>::size(), KeySorter);
} }
static int CDECL KeySorter(const Pair *a, const Pair *b) static int CDECL KeySorter(const Pair *a, const Pair *b)

@ -83,46 +83,6 @@ public:
} }
~SmallVector() = default; ~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<T>::data();
}
/**
* Get the pointer to the first item
*
* @return the pointer to the first item
*/
inline T *Begin()
{
return std::vector<T>::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<T>::data() + std::vector<T>::size();
}
/**
* Get the pointer behind the last valid item
*
* @return the pointer behind the last valid item
*/
inline T *End()
{
return std::vector<T>::data() + std::vector<T>::size();
}
}; };
/** /**

@ -1945,9 +1945,8 @@ void LoadUnloadStation(Station *st)
} }
/* Call the production machinery of industries */ /* Call the production machinery of industries */
const Industry * const *isend = _cargo_delivery_destinations.End(); for (Industry *iid : _cargo_delivery_destinations) {
for (Industry **iid = _cargo_delivery_destinations.Begin(); iid != isend; iid++) { TriggerIndustryProduction(iid);
TriggerIndustryProduction(*iid);
} }
_cargo_delivery_destinations.clear(); _cargo_delivery_destinations.clear();
} }

@ -511,12 +511,12 @@ void EngineOverrideManager::ResetToDefaultMapping()
*/ */
EngineID EngineOverrideManager::GetID(VehicleType type, uint16 grf_local_id, uint32 grfid) EngineID EngineOverrideManager::GetID(VehicleType type, uint16 grf_local_id, uint32 grfid)
{ {
const EngineIDMapping *end = this->End();
EngineID index = 0; EngineID index = 0;
for (const EngineIDMapping *eid = this->Begin(); eid != end; eid++, index++) { for (const EngineIDMapping &eid : *this) {
if (eid->type == type && eid->grfid == grfid && eid->internal_id == grf_local_id) { if (eid.type == type && eid.grfid == grfid && eid.internal_id == grf_local_id) {
return index; return index;
} }
index++;
} }
return INVALID_ENGINE; return INVALID_ENGINE;
} }
@ -549,14 +549,14 @@ void SetupEngines()
_engine_pool.CleanPool(); _engine_pool.CleanPool();
assert(_engine_mngr.size() >= _engine_mngr.NUM_DEFAULT_ENGINES); assert(_engine_mngr.size() >= _engine_mngr.NUM_DEFAULT_ENGINES);
const EngineIDMapping *end = _engine_mngr.End();
uint index = 0; 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 /* Assert is safe; there won't be more than 256 original vehicles
* in any case, and we just cleaned the pool. */ * in any case, and we just cleaned the pool. */
assert(Engine::CanAllocateItem()); 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); assert(e->index == index);
index++;
} }
} }

@ -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) /* 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 */ * generally, do not sort if there are less than 2 items */
if (size < 2) return; if (size < 2) return;
QSortT(el->Begin(), size, compare); QSortT(el->data(), size, compare);
} }
/** /**

@ -380,7 +380,7 @@ static void FiosGetFileList(SaveLoadOperation fop, fios_getlist_callback_proc *c
{ {
SortingBits order = _savegame_sort_order; SortingBits order = _savegame_sort_order;
_savegame_sort_order = SORT_BY_NAME | SORT_ASCENDING; _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; _savegame_sort_order = order;
} }
@ -724,10 +724,10 @@ const char *FindScenario(const ContentInfo *ci, bool md5sum)
{ {
_scanner.Scan(false); _scanner.Scan(false);
for (ScenarioIdentifier *id = _scanner.Begin(); id != _scanner.End(); id++) { for (ScenarioIdentifier &id : _scanner) {
if (md5sum ? (memcmp(id->md5sum, ci->md5sum, sizeof(id->md5sum)) == 0) if (md5sum ? (memcmp(id.md5sum, ci->md5sum, sizeof(id.md5sum)) == 0)
: (id->scenid == ci->unique_id)) { : (id.scenid == ci->unique_id)) {
return id->filename; return id.filename;
} }
} }

@ -139,7 +139,7 @@ public:
*/ */
inline const FiosItem *Begin() const inline const FiosItem *Begin() const
{ {
return this->files.Begin(); return this->files.data();
} }
/** /**
@ -148,7 +148,7 @@ public:
*/ */
inline const FiosItem *End() const inline const FiosItem *End() const
{ {
return this->files.End(); return this->Begin() + this->Length();
} }
/** /**

@ -57,9 +57,8 @@ void LoadCheckData::Clear()
this->current_date = 0; this->current_date = 0;
memset(&this->settings, 0, sizeof(this->settings)); memset(&this->settings, 0, sizeof(this->settings));
const CompanyPropertiesMap::iterator end = this->companies.End(); for (auto &pair : this->companies) {
for (CompanyPropertiesMap::iterator it = this->companies.Begin(); it != end; it++) { delete pair.second;
delete it->second;
} }
companies.clear(); companies.clear();
@ -531,10 +530,9 @@ public:
if (y > y_max) break; if (y > y_max) break;
/* Companies / AIs */ /* Companies / AIs */
CompanyPropertiesMap::const_iterator end = _load_check_data.companies.End(); for (auto &pair : _load_check_data.companies) {
for (CompanyPropertiesMap::const_iterator it = _load_check_data.companies.Begin(); it != end; it++) { SetDParam(0, pair.first + 1);
SetDParam(0, it->first + 1); const CompanyProperties &c = *pair.second;
const CompanyProperties &c = *it->second;
if (c.name != NULL) { if (c.name != NULL) {
SetDParam(1, STR_JUST_RAW_STRING); SetDParam(1, STR_JUST_RAW_STRING);
SetDParamStr(2, c.name); SetDParamStr(2, c.name);

@ -411,8 +411,8 @@ FreeTypeFontCache::~FreeTypeFontCache()
this->face = NULL; this->face = NULL;
this->ClearFontCache(); this->ClearFontCache();
for (FontTable::iterator iter = this->font_tables.Begin(); iter != this->font_tables.End(); iter++) { for (auto &iter : this->font_tables) {
free(iter->second.second); free(iter.second.second);
} }
} }
@ -633,7 +633,7 @@ GlyphID FreeTypeFontCache::MapCharToGlyph(WChar key)
const void *FreeTypeFontCache::GetFontTable(uint32 tag, size_t &length) const void *FreeTypeFontCache::GetFontTable(uint32 tag, size_t &length)
{ {
const FontTable::iterator iter = this->font_tables.Find(tag); 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; length = iter->second.first;
return iter->second.second; return iter->second.second;
} }

@ -147,7 +147,7 @@ struct StringListReader : StringReader {
* @param translation Are we reading a translation? * @param translation Are we reading a translation?
*/ */
StringListReader(StringData &data, const LanguageStrings *strings, bool master, bool 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); StringNameWriter id_writer(&this->string_names);
id_writer.WriteHeader(data); 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(); 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(); translation_reader.ParseFile();
if (_errors != 0) throw std::exception(); 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); TranslationWriter writer(&this->compiled_strings.back()->lines);
writer.WriteLang(data); writer.WriteLang(data);
} }
@ -360,10 +360,11 @@ void RegisterGameTranslation(Squirrel *engine)
if (SQ_FAILED(sq_get(vm, -2))) return; if (SQ_FAILED(sq_get(vm, -2))) return;
int idx = 0; int idx = 0;
for (const char * const *p = _current_data->string_names.Begin(); p != _current_data->string_names.End(); p++, idx++) { for (const char * const p : _current_data->string_names) {
sq_pushstring(vm, *p, -1); sq_pushstring(vm, p, -1);
sq_pushinteger(vm, idx); sq_pushinteger(vm, idx);
sq_rawset(vm, -3); sq_rawset(vm, -3);
idx++;
} }
sq_pop(vm, 2); sq_pop(vm, 2);
@ -391,9 +392,9 @@ void ReconsiderGameScriptLanguage()
assert(language != NULL); assert(language != NULL);
language++; language++;
for (LanguageStrings **p = _current_data->compiled_strings.Begin(); p != _current_data->compiled_strings.End(); p++) { for (LanguageStrings *p : _current_data->compiled_strings) {
if (strcmp((*p)->language, language) == 0) { if (strcmp(p->language, language) == 0) {
_current_data->cur_language = *p; _current_data->cur_language = p;
return; return;
} }
} }

@ -511,7 +511,7 @@ int DrawString(int left, int right, int top, const char *str, TextColour colour,
Layouter layout(str, INT32_MAX, colour, fontsize); Layouter layout(str, INT32_MAX, colour, fontsize);
if (layout.size() == 0) return 0; 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 last_line = top;
int first_line = bottom; int first_line = bottom;
for (const ParagraphLayouter::Line **iter = layout.Begin(); iter != layout.End(); iter++) { for (const ParagraphLayouter::Line *line : layout) {
const ParagraphLayouter::Line *line = *iter;
int line_height = line->GetLeading(); int line_height = line->GetLeading();
if (y >= top && y < bottom) { if (y >= top && y < bottom) {

@ -196,13 +196,13 @@ public:
/* ICU's ParagraphLayout cannot handle empty strings, so fake one. */ /* ICU's ParagraphLayout cannot handle empty strings, so fake one. */
buff[0] = ' '; buff[0] = ' ';
length = 1; length = 1;
fontMapping.End()[-1].first++; fontMapping.back().first++;
} }
/* Fill ICU's FontRuns with the right data. */ /* Fill ICU's FontRuns with the right data. */
icu::FontRuns runs(fontMapping.size()); icu::FontRuns runs(fontMapping.size());
for (FontMap::iterator iter = fontMapping.Begin(); iter != fontMapping.End(); iter++) { for (auto &pair : fontMapping) {
runs.add(iter->second, iter->first); runs.add(pair.second, pair.first);
} }
LEErrorCode status = LE_NO_ERROR; LEErrorCode status = LE_NO_ERROR;
@ -419,8 +419,8 @@ int FallbackParagraphLayout::FallbackVisualRun::GetLeading() const
int FallbackParagraphLayout::FallbackLine::GetLeading() const int FallbackParagraphLayout::FallbackLine::GetLeading() const
{ {
int leading = 0; int leading = 0;
for (const FallbackVisualRun * const *run = this->Begin(); run != this->End(); run++) { for (const FallbackVisualRun * const &run : *this) {
leading = max(leading, (*run)->GetLeading()); leading = max(leading, run->GetLeading());
} }
return leading; return leading;
@ -498,12 +498,12 @@ const ParagraphLayouter::Line *FallbackParagraphLayout::NextLine(int max_width)
if (*this->buffer == '\0') { if (*this->buffer == '\0') {
/* Only a newline. */ /* Only a newline. */
this->buffer = NULL; 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; return l;
} }
int offset = this->buffer - this->buffer_begin; int offset = this->buffer - this->buffer_begin;
FontMap::iterator iter = this->runs.Begin(); FontMap::iterator iter = this->runs.data();
while (iter->first <= offset) { while (iter->first <= offset) {
iter++; iter++;
assert(iter != this->runs.End()); assert(iter != this->runs.End());
@ -733,9 +733,9 @@ Layouter::Layouter(const char *str, int maxw, TextColour colour, FontSize fontsi
Dimension Layouter::GetBounds() Dimension Layouter::GetBounds()
{ {
Dimension d = { 0, 0 }; Dimension d = { 0, 0 };
for (const ParagraphLayouter::Line **l = this->Begin(); l != this->End(); l++) { for (const ParagraphLayouter::Line *l : *this) {
d.width = max<uint>(d.width, (*l)->GetWidth()); d.width = max<uint>(d.width, l->GetWidth());
d.height += (*l)->GetLeading(); d.height += l->GetLeading();
} }
return d; return d;
} }
@ -757,12 +757,12 @@ Point Layouter::GetCharPosition(const char *ch) const
size_t len = Utf8Decode(&c, str); size_t len = Utf8Decode(&c, str);
if (c == '\0' || c == '\n') break; if (c == '\0' || c == '\n') break;
str += len; str += len;
index += (*this->Begin())->GetInternalCharLength(c); index += this->front()->GetInternalCharLength(c);
} }
if (str == ch) { if (str == ch) {
/* Valid character. */ /* 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. */ /* Pointer to the end-of-string/line marker? Return total line width. */
if (*ch == '\0' || *ch == '\n') { if (*ch == '\0' || *ch == '\n') {
@ -795,7 +795,7 @@ Point Layouter::GetCharPosition(const char *ch) const
*/ */
const char *Layouter::GetCharAtPosition(int x) 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++) { for (int run_index = 0; run_index < line->CountRuns(); run_index++) {
const ParagraphLayouter::VisualRun *run = line->GetVisualRun(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) void Layouter::ResetFontCache(FontSize size)
{ {
for (FontColourMap::iterator it = fonts[size].Begin(); it != fonts[size].End(); ++it) { for (auto &pair : fonts[size]) {
delete it->second; delete pair.second;
} }
fonts[size].clear(); fonts[size].clear();

@ -127,11 +127,11 @@ private:
void AddChildren(GUIGroupList *source, GroupID parent, int indent) void AddChildren(GUIGroupList *source, GroupID parent, int indent)
{ {
for (const Group **g = source->Begin(); g != source->End(); g++) { for (const Group *g : *source) {
if ((*g)->parent != parent) continue; if (g->parent != parent) continue;
this->groups.push_back(*g); this->groups.push_back(g);
this->indents.push_back(indent); this->indents.push_back(indent);
AddChildren(source, (*g)->index, indent + 1); AddChildren(source, g->index, indent + 1);
} }
} }

@ -316,11 +316,11 @@ static void SaveLoadHotkeys(bool save)
IniFile *ini = new IniFile(); IniFile *ini = new IniFile();
ini->LoadFromDisk(_hotkeys_file, NO_DIRECTORY); ini->LoadFromDisk(_hotkeys_file, NO_DIRECTORY);
for (HotkeyList **list = _hotkey_lists->Begin(); list != _hotkey_lists->End(); ++list) { for (HotkeyList *list : *_hotkey_lists) {
if (save) { if (save) {
(*list)->Save(ini); list->Save(ini);
} else { } else {
(*list)->Load(ini); list->Load(ini);
} }
} }
@ -343,11 +343,11 @@ void SaveHotkeysToConfig()
void HandleGlobalHotkeys(WChar key, uint16 keycode) void HandleGlobalHotkeys(WChar key, uint16 keycode)
{ {
for (HotkeyList **list = _hotkey_lists->Begin(); list != _hotkey_lists->End(); ++list) { for (HotkeyList *list : *_hotkey_lists) {
if ((*list)->global_hotkey_handler == NULL) continue; if (list->global_hotkey_handler == NULL) continue;
int hotkey = (*list)->CheckMatch(keycode, true); int hotkey = list->CheckMatch(keycode, true);
if (hotkey >= 0 && ((*list)->global_hotkey_handler(hotkey) == ES_HANDLED)) return; if (hotkey >= 0 && (list->global_hotkey_handler(hotkey) == ES_HANDLED)) return;
} }
} }

@ -751,7 +751,7 @@ static void MidiThreadProc(void *)
block_time = playback_start_time + block.realtime * MIDITIME_TO_REFTIME; 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)); 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(); size_t remaining = block.data.size();
byte last_status = 0; byte last_status = 0;
while (remaining > 0) { while (remaining > 0) {

@ -336,7 +336,7 @@ static bool FixupMidiData(MidiFile &target)
last_ticktime = block.ticktime; last_ticktime = block.ticktime;
} else { } else {
byte *datadest = grow(merged_blocks.back().data, block.data.size()); 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); std::swap(merged_blocks, target.blocks);
@ -940,8 +940,8 @@ bool MidiFile::WriteSMF(const char *filename)
} }
/* Write each block data command */ /* Write each block data command */
byte *dp = block.data.Begin(); byte *dp = block.data.data();
while (dp < block.data.End()) { while (dp < block.data.data() + block.data.size()) {
/* Always zero delta time inside blocks */ /* Always zero delta time inside blocks */
if (needtime) { if (needtime) {
fputc(0, f); fputc(0, f);

@ -229,7 +229,7 @@ void CALLBACK TimerCallback(UINT uTimerID, UINT, DWORD_PTR dwUser, DWORD_PTR, DW
break; break;
} }
byte *data = block.data.Begin(); byte *data = block.data.data();
size_t remaining = block.data.size(); size_t remaining = block.data.size();
byte last_status = 0; byte last_status = 0;
while (remaining > 0) { while (remaining > 0) {

@ -200,8 +200,8 @@ void NetworkFindBroadcastIPs(NetworkAddressList *broadcast)
/* Now display to the debug all the detected ips */ /* Now display to the debug all the detected ips */
DEBUG(net, 3, "Detected broadcast addresses:"); DEBUG(net, 3, "Detected broadcast addresses:");
int i = 0; int i = 0;
for (NetworkAddress *addr = broadcast->Begin(); addr != broadcast->End(); addr++) { for (NetworkAddress &addr : *broadcast) {
addr->SetPort(NETWORK_DEFAULT_PORT); addr.SetPort(NETWORK_DEFAULT_PORT);
DEBUG(net, 3, "%d) %s", i++, addr->GetHostname()); DEBUG(net, 3, "%d) %s", i++, addr.GetHostname());
} }
} }

@ -93,5 +93,5 @@ void TCPConnecter::Connect()
/** Kill all connection attempts. */ /** Kill all connection attempts. */
/* static */ void TCPConnecter::KillAll() /* 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;
} }

@ -303,8 +303,8 @@ int NetworkHTTPSocketHandler::Receive()
struct timeval tv; struct timeval tv;
FD_ZERO(&read_fd); FD_ZERO(&read_fd);
for (NetworkHTTPSocketHandler **iter = _http_connections.Begin(); iter < _http_connections.End(); iter++) { for (NetworkHTTPSocketHandler *handler : _http_connections) {
FD_SET((*iter)->sock, &read_fd); FD_SET(handler->sock, &read_fd);
} }
tv.tv_sec = tv.tv_usec = 0; // don't block at all. tv.tv_sec = tv.tv_usec = 0; // don't block at all.

@ -54,13 +54,13 @@ public:
/* Check if the client is banned */ /* Check if the client is banned */
bool banned = false; bool banned = false;
for (char **iter = _network_ban_list.Begin(); iter != _network_ban_list.End(); iter++) { for (char *entry : _network_ban_list) {
banned = address.IsInNetmask(*iter); banned = address.IsInNetmask(entry);
if (banned) { if (banned) {
Packet p(Tban_packet); Packet p(Tban_packet);
p.PrepareToSend(); 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) { if (send(s, (const char*)p.buffer, p.size, 0) < 0) {
DEBUG(net, 0, "send failed with error %d", GET_LAST_ERROR()); DEBUG(net, 0, "send failed with error %d", GET_LAST_ERROR());
@ -111,16 +111,16 @@ public:
} }
/* take care of listener port */ /* take care of listener port */
for (SocketList::iterator s = sockets.Begin(); s != sockets.End(); s++) { for (auto &s : sockets) {
FD_SET(s->second, &read_fd); FD_SET(s.second, &read_fd);
} }
tv.tv_sec = tv.tv_usec = 0; // don't block at all. 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; if (select(FD_SETSIZE, &read_fd, &write_fd, NULL, &tv) < 0) return false;
/* accept clients.. */ /* accept clients.. */
for (SocketList::iterator s = sockets.Begin(); s != sockets.End(); s++) { for (auto &s : sockets) {
if (FD_ISSET(s->second, &read_fd)) AcceptClient(s->second); if (FD_ISSET(s.second, &read_fd)) AcceptClient(s.second);
} }
/* read stuff from clients */ /* read stuff from clients */
@ -145,8 +145,8 @@ public:
NetworkAddressList addresses; NetworkAddressList addresses;
GetBindAddresses(&addresses, port); GetBindAddresses(&addresses, port);
for (NetworkAddress *address = addresses.Begin(); address != addresses.End(); address++) { for (NetworkAddress &address : addresses) {
address->Listen(SOCK_STREAM, &sockets); address.Listen(SOCK_STREAM, &sockets);
} }
if (sockets.size() == 0) { if (sockets.size() == 0) {
@ -161,8 +161,8 @@ public:
/** Close the sockets we're listening on. */ /** Close the sockets we're listening on. */
static void CloseListeners() static void CloseListeners()
{ {
for (SocketList::iterator s = sockets.Begin(); s != sockets.End(); s++) { for (auto &s : sockets) {
closesocket(s->second); closesocket(s.second);
} }
sockets.clear(); sockets.clear();
DEBUG(net, 1, "[%s] closed listeners", Tsocket::GetName()); DEBUG(net, 1, "[%s] closed listeners", Tsocket::GetName());

@ -25,8 +25,8 @@
NetworkUDPSocketHandler::NetworkUDPSocketHandler(NetworkAddressList *bind) NetworkUDPSocketHandler::NetworkUDPSocketHandler(NetworkAddressList *bind)
{ {
if (bind != NULL) { if (bind != NULL) {
for (NetworkAddress *addr = bind->Begin(); addr != bind->End(); addr++) { for (NetworkAddress &addr : *bind) {
this->bind.push_back(*addr); this->bind.push_back(addr);
} }
} else { } else {
/* As hostname NULL and port 0/NULL don't go well when /* As hostname NULL and port 0/NULL don't go well when
@ -47,8 +47,8 @@ bool NetworkUDPSocketHandler::Listen()
/* Make sure socket is closed */ /* Make sure socket is closed */
this->Close(); this->Close();
for (NetworkAddress *addr = this->bind.Begin(); addr != this->bind.End(); addr++) { for (NetworkAddress &addr : this->bind) {
addr->Listen(SOCK_DGRAM, &this->sockets); addr.Listen(SOCK_DGRAM, &this->sockets);
} }
return this->sockets.size() != 0; return this->sockets.size() != 0;
@ -59,8 +59,8 @@ bool NetworkUDPSocketHandler::Listen()
*/ */
void NetworkUDPSocketHandler::Close() void NetworkUDPSocketHandler::Close()
{ {
for (SocketList::iterator s = this->sockets.Begin(); s != this->sockets.End(); s++) { for (auto &s : this->sockets) {
closesocket(s->second); closesocket(s.second);
} }
this->sockets.clear(); this->sockets.clear();
} }
@ -82,26 +82,26 @@ void NetworkUDPSocketHandler::SendPacket(Packet *p, NetworkAddress *recv, bool a
{ {
if (this->sockets.size() == 0) this->Listen(); 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 /* Make a local copy because if we resolve it we cannot
* easily unresolve it so we can resolve it later again. */ * easily unresolve it so we can resolve it later again. */
NetworkAddress send(*recv); NetworkAddress send(*recv);
/* Not the same type */ /* Not the same type */
if (!send.IsFamily(s->first.GetAddress()->ss_family)) continue; if (!send.IsFamily(s.first.GetAddress()->ss_family)) continue;
p->PrepareToSend(); p->PrepareToSend();
if (broadcast) { if (broadcast) {
/* Enable broadcast */ /* Enable broadcast */
unsigned long val = 1; 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()); DEBUG(net, 1, "[udp] setting broadcast failed with: %i", GET_LAST_ERROR());
} }
} }
/* Send the buffer */ /* 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()); DEBUG(net, 7, "[udp] sendto(%s)", send.GetAddressAsString());
/* Check for any errors, but ignore it otherwise */ /* Check for any errors, but ignore it otherwise */
@ -116,7 +116,7 @@ void NetworkUDPSocketHandler::SendPacket(Packet *p, NetworkAddress *recv, bool a
*/ */
void NetworkUDPSocketHandler::ReceivePackets() 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 for (int i = 0; i < 1000; i++) { // Do not infinitely loop when DoSing with UDP
struct sockaddr_storage client_addr; struct sockaddr_storage client_addr;
memset(&client_addr, 0, sizeof(client_addr)); memset(&client_addr, 0, sizeof(client_addr));
@ -125,8 +125,8 @@ void NetworkUDPSocketHandler::ReceivePackets()
socklen_t client_len = sizeof(client_addr); socklen_t client_len = sizeof(client_addr);
/* Try to receive anything */ /* Try to receive anything */
SetNonBlocking(s->second); // Some OSes seem to lose the non-blocking status of the socket 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); 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? */ /* Did we get the bytes for the base header of the packet? */
if (nbytes <= 0) break; // No data, i.e. no packet if (nbytes <= 0) break; // No data, i.e. no packet

@ -632,8 +632,8 @@ void NetworkAddServer(const char *b)
*/ */
void GetBindAddresses(NetworkAddressList *addresses, uint16 port) void GetBindAddresses(NetworkAddressList *addresses, uint16 port)
{ {
for (char **iter = _network_bind_list.Begin(); iter != _network_bind_list.End(); iter++) { for (char *iter : _network_bind_list) {
addresses->emplace_back(*iter, port); addresses->emplace_back(iter, port);
} }
/* No address, so bind to everything. */ /* No address, so bind to everything. */

@ -110,7 +110,7 @@ struct PacketReader : LoadFilter {
{ {
this->read_bytes = 0; this->read_bytes = 0;
this->block = this->blocks.Begin(); this->block = this->blocks.data();
this->buf = *this->block++; this->buf = *this->block++;
this->bufe = this->buf + CHUNK; this->bufe = this->buf + CHUNK;
} }

@ -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; if (ci->state == ContentInfo::UNSELECTED && ci->filesize == 0) ci->state = ContentInfo::DOES_NOT_EXIST;
/* Do we already have a stub for this? */ /* Do we already have a stub for this? */
for (ContentIterator iter = this->infos.Begin(); iter != this->infos.End(); iter++) { for (ContentInfo *ici : this->infos) {
ContentInfo *ici = *iter;
if (ici->type == ci->type && ici->unique_id == ci->unique_id && if (ici->type == ci->type && ici->unique_id == ci->unique_id &&
memcmp(ci->md5sum, ici->md5sum, sizeof(ci->md5sum)) == 0) { memcmp(ci->md5sum, ici->md5sum, sizeof(ci->md5sum)) == 0) {
/* Preserve the name if possible */ /* Preserve the name if possible */
@ -168,8 +167,8 @@ bool ClientNetworkContentSocketHandler::Receive_SERVER_INFO(Packet *p)
this->infos.push_back(ci); this->infos.push_back(ci);
/* Incoming data means that we might need to reconsider dependencies */ /* Incoming data means that we might need to reconsider dependencies */
for (ContentIterator iter = this->infos.Begin(); iter != this->infos.End(); iter++) { for (ContentInfo *ici : this->infos) {
this->CheckDependencyState(*iter); this->CheckDependencyState(ici);
} }
this->OnReceiveContentInfo(ci); 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); Packet *p = new Packet(send_md5sum ? PACKET_CONTENT_CLIENT_INFO_EXTID_MD5 : PACKET_CONTENT_CLIENT_INFO_EXTID);
p->Send_uint8(cv->size()); p->Send_uint8(cv->size());
for (ContentIterator iter = cv->Begin(); iter != cv->End(); iter++) { for (const ContentInfo *ci : *cv) {
const ContentInfo *ci = *iter;
p->Send_uint8((byte)ci->type); p->Send_uint8((byte)ci->type);
p->Send_uint32(ci->unique_id); p->Send_uint32(ci->unique_id);
if (!send_md5sum) continue; if (!send_md5sum) continue;
@ -266,11 +264,9 @@ void ClientNetworkContentSocketHandler::RequestContentList(ContentVector *cv, bo
this->SendPacket(p); this->SendPacket(p);
for (ContentIterator iter = cv->Begin(); iter != cv->End(); iter++) { for (ContentInfo *ci : *cv) {
ContentInfo *ci = *iter;
bool found = false; bool found = false;
for (ContentIterator iter2 = this->infos.Begin(); iter2 != this->infos.End(); iter2++) { for (ContentInfo *ci2 : this->infos) {
ContentInfo *ci2 = *iter2;
if (ci->type == ci2->type && ci->unique_id == ci2->unique_id && if (ci->type == ci2->type && ci->unique_id == ci2->unique_id &&
(!send_md5sum || memcmp(ci->md5sum, ci2->md5sum, sizeof(ci->md5sum)) == 0)) { (!send_md5sum || memcmp(ci->md5sum, ci2->md5sum, sizeof(ci->md5sum)) == 0)) {
found = true; found = true;
@ -296,8 +292,7 @@ void ClientNetworkContentSocketHandler::DownloadSelectedContent(uint &files, uin
bytes = 0; bytes = 0;
ContentIDList content; ContentIDList content;
for (ContentIterator iter = this->infos.Begin(); iter != this->infos.End(); iter++) { for (const ContentInfo *ci : this->infos) {
const ContentInfo *ci = *iter;
if (!ci->IsSelected() || ci->state == ContentInfo::ALREADY_HERE) continue; if (!ci->IsSelected() || ci->state == ContentInfo::ALREADY_HERE) continue;
content.push_back(ci->id); content.push_back(ci->id);
@ -333,8 +328,8 @@ void ClientNetworkContentSocketHandler::DownloadSelectedContentHTTP(const Conten
const char *lastof = content_request + bytes - 1; const char *lastof = content_request + bytes - 1;
char *p = content_request; char *p = content_request;
for (const ContentID *id = content.Begin(); id != content.End(); id++) { for (const ContentID &id : content) {
p += seprintf(p, lastof, "%d\n", *id); p += seprintf(p, lastof, "%d\n", id);
} }
this->http_response_index = -1; this->http_response_index = -1;
@ -351,7 +346,7 @@ void ClientNetworkContentSocketHandler::DownloadSelectedContentHTTP(const Conten
void ClientNetworkContentSocketHandler::DownloadSelectedContentFallback(const ContentIDList &content) void ClientNetworkContentSocketHandler::DownloadSelectedContentFallback(const ContentIDList &content)
{ {
uint count = content.size(); uint count = content.size();
const ContentID *content_ids = content.Begin(); const ContentID *content_ids = content.data();
this->Connect(); this->Connect();
while (count > 0) { 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'; } #define check_and_terminate(p) { check_not_null(p); *(p) = '\0'; }
for (;;) { 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'); char *p = strchr(str, '\n');
check_and_terminate(p); check_and_terminate(p);
@ -713,7 +708,7 @@ ClientNetworkContentSocketHandler::~ClientNetworkContentSocketHandler()
delete this->curInfo; delete this->curInfo;
if (this->curFile != NULL) fclose(this->curFile); 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. */ /** Connect to the content server. */
@ -807,8 +802,7 @@ void ClientNetworkContentSocketHandler::DownloadContentInfo(ContentID cid)
*/ */
ContentInfo *ClientNetworkContentSocketHandler::GetContent(ContentID cid) ContentInfo *ClientNetworkContentSocketHandler::GetContent(ContentID cid)
{ {
for (ContentIterator iter = this->infos.Begin(); iter != this->infos.End(); iter++) { for (ContentInfo *ci : this->infos) {
ContentInfo *ci = *iter;
if (ci->id == cid) return ci; if (ci->id == cid) return ci;
} }
return NULL; return NULL;
@ -844,8 +838,7 @@ void ClientNetworkContentSocketHandler::Unselect(ContentID cid)
/** Select everything we can select */ /** Select everything we can select */
void ClientNetworkContentSocketHandler::SelectAll() void ClientNetworkContentSocketHandler::SelectAll()
{ {
for (ContentIterator iter = this->infos.Begin(); iter != this->infos.End(); iter++) { for (ContentInfo *ci : this->infos) {
ContentInfo *ci = *iter;
if (ci->state == ContentInfo::UNSELECTED) { if (ci->state == ContentInfo::UNSELECTED) {
ci->state = ContentInfo::SELECTED; ci->state = ContentInfo::SELECTED;
this->CheckDependencyState(ci); this->CheckDependencyState(ci);
@ -856,8 +849,7 @@ void ClientNetworkContentSocketHandler::SelectAll()
/** Select everything that's an update for something we've got */ /** Select everything that's an update for something we've got */
void ClientNetworkContentSocketHandler::SelectUpgrade() void ClientNetworkContentSocketHandler::SelectUpgrade()
{ {
for (ContentIterator iter = this->infos.Begin(); iter != this->infos.End(); iter++) { for (ContentInfo *ci : this->infos) {
ContentInfo *ci = *iter;
if (ci->state == ContentInfo::UNSELECTED && ci->upgrade) { if (ci->state == ContentInfo::UNSELECTED && ci->upgrade) {
ci->state = ContentInfo::SELECTED; ci->state = ContentInfo::SELECTED;
this->CheckDependencyState(ci); this->CheckDependencyState(ci);
@ -868,8 +860,7 @@ void ClientNetworkContentSocketHandler::SelectUpgrade()
/** Unselect everything that we've not downloaded so far. */ /** Unselect everything that we've not downloaded so far. */
void ClientNetworkContentSocketHandler::UnselectAll() void ClientNetworkContentSocketHandler::UnselectAll()
{ {
for (ContentIterator iter = this->infos.Begin(); iter != this->infos.End(); iter++) { for (ContentInfo *ci : this->infos) {
ContentInfo *ci = *iter;
if (ci->IsSelected() && ci->state != ContentInfo::ALREADY_HERE) ci->state = ContentInfo::UNSELECTED; 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 void ClientNetworkContentSocketHandler::ReverseLookupDependency(ConstContentVector &parents, const ContentInfo *child) const
{ {
for (ConstContentIterator iter = this->infos.Begin(); iter != this->infos.End(); iter++) { for (const ContentInfo * const &ci : this->infos) {
const ContentInfo *ci = *iter;
if (ci == child) continue; if (ci == child) continue;
for (uint i = 0; i < ci->dependency_count; i++) { for (uint i = 0; i < ci->dependency_count; i++) {
@ -929,8 +919,8 @@ void ClientNetworkContentSocketHandler::ReverseLookupTreeDependency(ConstContent
ConstContentVector parents; ConstContentVector parents;
this->ReverseLookupDependency(parents, tree[i]); this->ReverseLookupDependency(parents, tree[i]);
for (ConstContentIterator piter = parents.Begin(); piter != parents.End(); piter++) { for (const ContentInfo *ci : parents) {
include(tree, *piter); include(tree, ci);
} }
} }
} }
@ -965,8 +955,7 @@ void ClientNetworkContentSocketHandler::CheckDependencyState(ContentInfo *ci)
* we automatically selected them. */ * we automatically selected them. */
ConstContentVector parents; ConstContentVector parents;
this->ReverseLookupDependency(parents, ci); this->ReverseLookupDependency(parents, ci);
for (ConstContentIterator iter = parents.Begin(); iter != parents.End(); iter++) { for (const ContentInfo *c : parents) {
const ContentInfo *c = *iter;
if (!c->IsSelected()) continue; if (!c->IsSelected()) continue;
this->Unselect(c->id); this->Unselect(c->id);
@ -987,9 +976,9 @@ void ClientNetworkContentSocketHandler::CheckDependencyState(ContentInfo *ci)
/* First check whether anything depends on us */ /* First check whether anything depends on us */
int sel_count = 0; int sel_count = 0;
bool force_selection = false; bool force_selection = false;
for (ConstContentIterator iter = parents.Begin(); iter != parents.End(); iter++) { for (const ContentInfo *ci : parents) {
if ((*iter)->IsSelected()) sel_count++; if (ci->IsSelected()) sel_count++;
if ((*iter)->state == ContentInfo::SELECTED) force_selection = true; if (ci->state == ContentInfo::SELECTED) force_selection = true;
} }
if (sel_count == 0) { if (sel_count == 0) {
/* Nothing depends on us */ /* Nothing depends on us */
@ -1004,8 +993,8 @@ void ClientNetworkContentSocketHandler::CheckDependencyState(ContentInfo *ci)
this->ReverseLookupTreeDependency(parents, c); this->ReverseLookupTreeDependency(parents, c);
/* Is there anything that is "force" selected?, if so... we're done. */ /* Is there anything that is "force" selected?, if so... we're done. */
for (ConstContentIterator iter = parents.Begin(); iter != parents.End(); iter++) { for (const ContentInfo *ci : parents) {
if ((*iter)->state != ContentInfo::SELECTED) continue; if (ci->state != ContentInfo::SELECTED) continue;
force_selection = true; force_selection = true;
break; break;
@ -1018,12 +1007,11 @@ void ClientNetworkContentSocketHandler::CheckDependencyState(ContentInfo *ci)
* After that's done run over them once again to test their children * 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 * to unselect. Don't do it immediately because it'll do exactly what
* we're doing now. */ * we're doing now. */
for (ConstContentIterator iter = parents.Begin(); iter != parents.End(); iter++) { for (const ContentInfo *c : parents) {
const ContentInfo *c = *iter;
if (c->state == ContentInfo::AUTOSELECTED) this->Unselect(c->id); if (c->state == ContentInfo::AUTOSELECTED) this->Unselect(c->id);
} }
for (ConstContentIterator iter = parents.Begin(); iter != parents.End(); iter++) { for (const ContentInfo *c : parents) {
this->CheckDependencyState(this->GetContent((*iter)->id)); this->CheckDependencyState(this->GetContent(c->id));
} }
} }
} }
@ -1031,7 +1019,7 @@ void ClientNetworkContentSocketHandler::CheckDependencyState(ContentInfo *ci)
/** Clear all downloaded content information. */ /** Clear all downloaded content information. */
void ClientNetworkContentSocketHandler::Clear() 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->infos.clear();
this->requested.clear(); this->requested.clear();
@ -1041,37 +1029,37 @@ void ClientNetworkContentSocketHandler::Clear()
void ClientNetworkContentSocketHandler::OnConnect(bool success) 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; ContentCallback *cb = *iter;
cb->OnConnect(success); cb->OnConnect(success);
if (iter != this->callbacks.End() && *iter == cb) iter++; if (iter != this->callbacks.end() && *iter == cb) iter++;
} }
} }
void ClientNetworkContentSocketHandler::OnDisconnect() 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; ContentCallback *cb = *iter;
cb->OnDisconnect(); cb->OnDisconnect();
if (iter != this->callbacks.End() && *iter == cb) iter++; if (iter != this->callbacks.end() && *iter == cb) iter++;
} }
} }
void ClientNetworkContentSocketHandler::OnReceiveContentInfo(const ContentInfo *ci) 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; ContentCallback *cb = *iter;
cb->OnReceiveContentInfo(ci); 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) 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; ContentCallback *cb = *iter;
cb->OnDownloadProgress(ci, bytes); 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; 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; ContentCallback *cb = *iter;
cb->OnDownloadComplete(cid); cb->OnDownloadComplete(cid);
if (iter != this->callbacks.End() && *iter == cb) iter++; if (iter != this->callbacks.end() && *iter == cb) iter++;
} }
} }

@ -131,11 +131,11 @@ public:
/** Get the number of content items we know locally. */ /** Get the number of content items we know locally. */
uint Length() const { return this->infos.size(); } uint Length() const { return this->infos.size(); }
/** Get the begin of the content inf iterator. */ /** 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. */ /** Get the nth position of the content inf iterator. */
ConstContentIterator Get(uint32 index) const { return this->infos.data() + index; } ConstContentIterator Get(uint32 index) const { return this->infos.data() + index; }
/** Get the end of the content inf iterator. */ /** 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(); void Clear();

@ -176,8 +176,8 @@ public:
~NetworkContentDownloadStatusWindow() ~NetworkContentDownloadStatusWindow()
{ {
TarScanner::Mode mode = TarScanner::NONE; TarScanner::Mode mode = TarScanner::NONE;
for (ContentType *iter = this->receivedTypes.Begin(); iter != this->receivedTypes.End(); iter++) { for (auto ctype : this->receivedTypes) {
switch (*iter) { switch (ctype) {
case CONTENT_TYPE_AI: case CONTENT_TYPE_AI:
case CONTENT_TYPE_AI_LIBRARY: case CONTENT_TYPE_AI_LIBRARY:
/* AI::Rescan calls the scanner. */ /* AI::Rescan calls the scanner. */
@ -210,8 +210,8 @@ public:
TarScanner::DoScan(mode); TarScanner::DoScan(mode);
/* Tell all the backends about what we've downloaded */ /* Tell all the backends about what we've downloaded */
for (ContentType *iter = this->receivedTypes.Begin(); iter != this->receivedTypes.End(); iter++) { for (auto ctype : this->receivedTypes) {
switch (*iter) { switch (ctype) {
case CONTENT_TYPE_AI: case CONTENT_TYPE_AI:
case CONTENT_TYPE_AI_LIBRARY: case CONTENT_TYPE_AI_LIBRARY:
AI::Rescan(); AI::Rescan();
@ -333,8 +333,7 @@ class NetworkContentListWindow : public Window, ContentCallback {
pos = strecpy(pos, "do=searchgrfid&q=", last); pos = strecpy(pos, "do=searchgrfid&q=", last);
bool first = true; bool first = true;
for (ConstContentIterator iter = this->content.Begin(); iter != this->content.End(); iter++) { for (const ContentInfo *ci : this->content) {
const ContentInfo *ci = *iter;
if (ci->state != ContentInfo::DOES_NOT_EXIST) continue; if (ci->state != ContentInfo::DOES_NOT_EXIST) continue;
if (!first) pos = strecpy(pos, ",", last); 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 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; int text_y_offset = WD_MATRIX_TOP + (line_height - FONT_HEIGHT_NORMAL) / 2;
uint y = r.top; 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; 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); 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 buf[DRAW_STRING_BUFFER] = "";
char *p = buf; char *p = buf;
for (ConstContentIterator iter = tree.Begin(); iter != tree.End(); iter++) { for (const ContentInfo *ci : tree) {
const ContentInfo *ci = *iter;
if (ci == this->selected || ci->state != ContentInfo::SELECTED) continue; if (ci == this->selected || ci->state != ContentInfo::SELECTED) continue;
p += seprintf(p, lastof(buf), buf == p ? "%s" : ", %s", ci->name); p += seprintf(p, lastof(buf), buf == p ? "%s" : ", %s", ci->name);
@ -985,8 +988,7 @@ public:
this->filesize_sum = 0; this->filesize_sum = 0;
bool show_select_all = false; bool show_select_all = false;
bool show_select_upgrade = false; bool show_select_upgrade = false;
for (ConstContentIterator iter = this->content.Begin(); iter != this->content.End(); iter++) { for (const ContentInfo *ci : this->content) {
const ContentInfo *ci = *iter;
switch (ci->state) { switch (ci->state) {
case ContentInfo::SELECTED: case ContentInfo::SELECTED:
case ContentInfo::AUTOSELECTED: 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); ShowErrorMessage(STR_CONTENT_NO_ZLIB, STR_CONTENT_NO_ZLIB_SUB, WL_ERROR);
/* Connection failed... clean up the mess */ /* Connection failed... clean up the mess */
if (cv != NULL) { if (cv != NULL) {
for (ContentIterator iter = cv->Begin(); iter != cv->End(); iter++) delete *iter; for (ContentInfo *ci : *cv) delete ci;
} }
#endif /* WITH_ZLIB */ #endif /* WITH_ZLIB */
} }

@ -1045,8 +1045,8 @@ void ShowNetworkGameWindow()
if (first) { if (first) {
first = false; first = false;
/* Add all servers from the config file to our list. */ /* Add all servers from the config file to our list. */
for (char **iter = _network_host_list.Begin(); iter != _network_host_list.End(); iter++) { for (char *iter : _network_host_list) {
NetworkAddServer(*iter); NetworkAddServer(iter);
} }
} }
@ -1783,8 +1783,8 @@ struct NetworkClientListPopupWindow : Window {
void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
{ {
Dimension d = *size; Dimension d = *size;
for (const ClientListAction *action = this->actions.Begin(); action != this->actions.End(); action++) { for (const ClientListAction &action : this->actions) {
d = maxdim(GetStringBoundingBox(action->name), d); d = maxdim(GetStringBoundingBox(action.name), d);
} }
d.height *= this->actions.size(); d.height *= this->actions.size();
@ -1798,7 +1798,7 @@ struct NetworkClientListPopupWindow : Window {
/* Draw the actions */ /* Draw the actions */
int sel = this->sel_index; int sel = this->sel_index;
int y = r.top + WD_FRAMERECT_TOP; 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; TextColour colour;
if (sel-- == 0) { // Selected item, highlight it if (sel-- == 0) { // Selected item, highlight it
GfxFillRect(r.left + 1, y, r.right - 1, y + FONT_HEIGHT_NORMAL - 1, PC_BLACK); 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; 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;
} }
} }

@ -2095,8 +2095,8 @@ uint NetworkServerKickOrBanIP(const char *ip, bool ban)
/* Add address to ban-list */ /* Add address to ban-list */
if (ban) { if (ban) {
bool contains = false; bool contains = false;
for (char **iter = _network_ban_list.Begin(); iter != _network_ban_list.End(); iter++) { for (char *iter : _network_ban_list) {
if (strcmp(*iter, ip) == 0) { if (strcmp(iter, ip) == 0) {
contains = true; contains = true;
break; break;
} }

@ -495,12 +495,12 @@ void ClientNetworkUDPSocketHandler::HandleIncomingNetworkGameInfoGRFConfig(GRFCo
/** Broadcast to all ips */ /** Broadcast to all ips */
static void NetworkUDPBroadCast(NetworkUDPSocketHandler *socket) 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); 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);
} }
} }

@ -391,9 +391,8 @@ void CDECL grfmsg(int severity, const char *str, ...)
*/ */
static GRFFile *GetFileByGRFID(uint32 grfid) static GRFFile *GetFileByGRFID(uint32 grfid)
{ {
const GRFFile * const *end = _grf_files.End(); for (GRFFile * const file : _grf_files) {
for (GRFFile * const *file = _grf_files.Begin(); file != end; file++) { if (file->grfid == grfid) return file;
if ((*file)->grfid == grfid) return *file;
} }
return NULL; return NULL;
} }
@ -405,9 +404,8 @@ static GRFFile *GetFileByGRFID(uint32 grfid)
*/ */
static GRFFile *GetFileByFilename(const char *filename) static GRFFile *GetFileByFilename(const char *filename)
{ {
const GRFFile * const *end = _grf_files.End(); for (GRFFile * const file : _grf_files) {
for (GRFFile * const *file = _grf_files.Begin(); file != end; file++) { if (strcmp(file->filename, filename) == 0) return file;
if (strcmp((*file)->filename, filename) == 0) return *file;
} }
return NULL; 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 */ /* On error, bail out immediately. Temporary GRF data was already freed */
if (_cur.skip_sprites < 0) return CIR_DISABLED; if (_cur.skip_sprites < 0) return CIR_DISABLED;
} }
dts->Clone(tmp_layout.Begin()); dts->Clone(tmp_layout.data());
} }
break; break;
@ -4826,7 +4824,7 @@ static void NewSpriteGroup(ByteReader *buf)
group->num_adjusts = adjusts.size(); group->num_adjusts = adjusts.size();
group->adjusts = MallocT<DeterministicSpriteGroupAdjust>(group->num_adjusts); group->adjusts = MallocT<DeterministicSpriteGroupAdjust>(group->num_adjusts);
MemCpyT(group->adjusts, adjusts.Begin(), group->num_adjusts); MemCpyT(group->adjusts, adjusts.data(), group->num_adjusts);
std::vector<DeterministicSpriteGroupRange> ranges; std::vector<DeterministicSpriteGroupRange> ranges;
ranges.resize(buf->ReadByte()); ranges.resize(buf->ReadByte());
@ -8094,9 +8092,8 @@ static void InitializeGRFSpecial()
/** Reset and clear all NewGRF stations */ /** Reset and clear all NewGRF stations */
static void ResetCustomStations() static void ResetCustomStations()
{ {
const GRFFile * const *end = _grf_files.End(); for (GRFFile * const file : _grf_files) {
for (GRFFile **file = _grf_files.Begin(); file != end; file++) { StationSpec **&stations = file->stations;
StationSpec **&stations = (*file)->stations;
if (stations == NULL) continue; if (stations == NULL) continue;
for (uint i = 0; i < NUM_STATIONS_PER_GRF; i++) { for (uint i = 0; i < NUM_STATIONS_PER_GRF; i++) {
if (stations[i] == NULL) continue; if (stations[i] == NULL) continue;
@ -8129,9 +8126,8 @@ static void ResetCustomStations()
/** Reset and clear all NewGRF houses */ /** Reset and clear all NewGRF houses */
static void ResetCustomHouses() static void ResetCustomHouses()
{ {
const GRFFile * const *end = _grf_files.End(); for (GRFFile * const file : _grf_files) {
for (GRFFile **file = _grf_files.Begin(); file != end; file++) { HouseSpec **&housespec = file->housespec;
HouseSpec **&housespec = (*file)->housespec;
if (housespec == NULL) continue; if (housespec == NULL) continue;
for (uint i = 0; i < NUM_HOUSES_PER_GRF; i++) { for (uint i = 0; i < NUM_HOUSES_PER_GRF; i++) {
free(housespec[i]); free(housespec[i]);
@ -8145,9 +8141,8 @@ static void ResetCustomHouses()
/** Reset and clear all NewGRF airports */ /** Reset and clear all NewGRF airports */
static void ResetCustomAirports() static void ResetCustomAirports()
{ {
const GRFFile * const *end = _grf_files.End(); for (GRFFile * const file : _grf_files) {
for (GRFFile **file = _grf_files.Begin(); file != end; file++) { AirportSpec **aslist = file->airportspec;
AirportSpec **aslist = (*file)->airportspec;
if (aslist != NULL) { if (aslist != NULL) {
for (uint i = 0; i < NUM_AIRPORTS_PER_GRF; i++) { for (uint i = 0; i < NUM_AIRPORTS_PER_GRF; i++) {
AirportSpec *as = aslist[i]; AirportSpec *as = aslist[i];
@ -8166,10 +8161,10 @@ static void ResetCustomAirports()
} }
} }
free(aslist); free(aslist);
(*file)->airportspec = NULL; file->airportspec = NULL;
} }
AirportTileSpec **&airporttilespec = (*file)->airtspec; AirportTileSpec **&airporttilespec = file->airtspec;
if (airporttilespec != NULL) { if (airporttilespec != NULL) {
for (uint i = 0; i < NUM_AIRPORTTILES_PER_GRF; i++) { for (uint i = 0; i < NUM_AIRPORTTILES_PER_GRF; i++) {
free(airporttilespec[i]); free(airporttilespec[i]);
@ -8183,10 +8178,9 @@ static void ResetCustomAirports()
/** Reset and clear all NewGRF industries */ /** Reset and clear all NewGRF industries */
static void ResetCustomIndustries() static void ResetCustomIndustries()
{ {
const GRFFile * const *end = _grf_files.End(); for (GRFFile * const file : _grf_files) {
for (GRFFile **file = _grf_files.Begin(); file != end; file++) { IndustrySpec **&industryspec = file->industryspec;
IndustrySpec **&industryspec = (*file)->industryspec; IndustryTileSpec **&indtspec = file->indtspec;
IndustryTileSpec **&indtspec = (*file)->indtspec;
/* We are verifiying both tiles and industries specs loaded from the grf file /* We are verifiying both tiles and industries specs loaded from the grf file
* First, let's deal with industryspec */ * First, let's deal with industryspec */
@ -8223,9 +8217,8 @@ static void ResetCustomIndustries()
/** Reset and clear all NewObjects */ /** Reset and clear all NewObjects */
static void ResetCustomObjects() static void ResetCustomObjects()
{ {
const GRFFile * const *end = _grf_files.End(); for (GRFFile * const file : _grf_files) {
for (GRFFile **file = _grf_files.Begin(); file != end; file++) { ObjectSpec **&objectspec = file->objectspec;
ObjectSpec **&objectspec = (*file)->objectspec;
if (objectspec == NULL) continue; if (objectspec == NULL) continue;
for (uint i = 0; i < NUM_OBJECTS_PER_GRF; i++) { for (uint i = 0; i < NUM_OBJECTS_PER_GRF; i++) {
free(objectspec[i]); free(objectspec[i]);
@ -8239,9 +8232,8 @@ static void ResetCustomObjects()
/** Reset and clear all NewGRFs */ /** Reset and clear all NewGRFs */
static void ResetNewGRF() static void ResetNewGRF()
{ {
const GRFFile * const *end = _grf_files.End(); for (GRFFile * const file : _grf_files) {
for (GRFFile **file = _grf_files.Begin(); file != end; file++) { delete file;
delete *file;
} }
_grf_files.clear(); _grf_files.clear();
@ -8760,9 +8752,8 @@ static void FinaliseHouseArray()
* On the other hand, why 1930? Just 'fix' the houses with the lowest * On the other hand, why 1930? Just 'fix' the houses with the lowest
* minimum introduction date to 0. * minimum introduction date to 0.
*/ */
const GRFFile * const *end = _grf_files.End(); for (GRFFile * const file : _grf_files) {
for (GRFFile **file = _grf_files.Begin(); file != end; file++) { HouseSpec **&housespec = file->housespec;
HouseSpec **&housespec = (*file)->housespec;
if (housespec == NULL) continue; if (housespec == NULL) continue;
for (int i = 0; i < NUM_HOUSES_PER_GRF; i++) { 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 *next2 = (i + 2 < NUM_HOUSES_PER_GRF ? housespec[i + 2] : NULL);
const HouseSpec *next3 = (i + 3 < NUM_HOUSES_PER_GRF ? housespec[i + 3] : 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); _house_mngr.SetEntitySpec(hs);
} }
@ -8823,10 +8814,9 @@ static void FinaliseHouseArray()
*/ */
static void FinaliseIndustriesArray() static void FinaliseIndustriesArray()
{ {
const GRFFile * const *end = _grf_files.End(); for (GRFFile * const file : _grf_files) {
for (GRFFile **file = _grf_files.Begin(); file != end; file++) { IndustrySpec **&industryspec = file->industryspec;
IndustrySpec **&industryspec = (*file)->industryspec; IndustryTileSpec **&indtspec = file->indtspec;
IndustryTileSpec **&indtspec = (*file)->indtspec;
if (industryspec != NULL) { if (industryspec != NULL) {
for (int i = 0; i < NUM_INDUSTRYTYPES_PER_GRF; i++) { for (int i = 0; i < NUM_INDUSTRYTYPES_PER_GRF; i++) {
IndustrySpec *indsp = industryspec[i]; IndustrySpec *indsp = industryspec[i];
@ -8894,9 +8884,8 @@ static void FinaliseIndustriesArray()
*/ */
static void FinaliseObjectsArray() static void FinaliseObjectsArray()
{ {
const GRFFile * const *end = _grf_files.End(); for (GRFFile * const file : _grf_files) {
for (GRFFile **file = _grf_files.Begin(); file != end; file++) { ObjectSpec **&objectspec = file->objectspec;
ObjectSpec **&objectspec = (*file)->objectspec;
if (objectspec != NULL) { if (objectspec != NULL) {
for (int i = 0; i < NUM_OBJECTS_PER_GRF; i++) { for (int i = 0; i < NUM_OBJECTS_PER_GRF; i++) {
if (objectspec[i] != NULL && objectspec[i]->grf_prop.grffile != NULL && objectspec[i]->enabled) { if (objectspec[i] != NULL && objectspec[i]->grf_prop.grffile != NULL && objectspec[i]->enabled) {
@ -8914,9 +8903,8 @@ static void FinaliseObjectsArray()
*/ */
static void FinaliseAirportsArray() static void FinaliseAirportsArray()
{ {
const GRFFile * const *end = _grf_files.End(); for (GRFFile * const file : _grf_files) {
for (GRFFile **file = _grf_files.Begin(); file != end; file++) { AirportSpec **&airportspec = file->airportspec;
AirportSpec **&airportspec = (*file)->airportspec;
if (airportspec != NULL) { if (airportspec != NULL) {
for (int i = 0; i < NUM_AIRPORTS_PER_GRF; i++) { for (int i = 0; i < NUM_AIRPORTS_PER_GRF; i++) {
if (airportspec[i] != NULL && airportspec[i]->enabled) { 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) { if (airporttilespec != NULL) {
for (uint i = 0; i < NUM_AIRPORTTILES_PER_GRF; i++) { for (uint i = 0; i < NUM_AIRPORTTILES_PER_GRF; i++) {
if (airporttilespec[i] != NULL && airporttilespec[i]->enabled) { if (airporttilespec[i] != NULL && airporttilespec[i]->enabled) {
@ -9286,10 +9274,9 @@ static void FinalisePriceBaseMultipliers()
} }
/* Apply fallback prices for grf version < 8 */ /* Apply fallback prices for grf version < 8 */
const GRFFile * const *end = _grf_files.End(); for (GRFFile * const file : _grf_files) {
for (GRFFile **file = _grf_files.Begin(); file != end; file++) { if (file->grf_version >= 8) continue;
if ((*file)->grf_version >= 8) continue; PriceMultipliers &price_base_multipliers = file->price_base_multipliers;
PriceMultipliers &price_base_multipliers = (*file)->price_base_multipliers;
for (Price p = PR_BEGIN; p < PR_END; p++) { for (Price p = PR_BEGIN; p < PR_END; p++) {
Price fallback_price = _price_base_specs[p].fallback_price; Price fallback_price = _price_base_specs[p].fallback_price;
if (fallback_price != INVALID_PRICE && price_base_multipliers[p] == INVALID_PRICE_MODIFIER) { 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 */ /* Decide local/global scope of price base multipliers */
for (GRFFile **file = _grf_files.Begin(); file != end; file++) { for (GRFFile * const file : _grf_files) {
PriceMultipliers &price_base_multipliers = (*file)->price_base_multipliers; PriceMultipliers &price_base_multipliers = file->price_base_multipliers;
for (Price p = PR_BEGIN; p < PR_END; p++) { for (Price p = PR_BEGIN; p < PR_END; p++) {
if (price_base_multipliers[p] == INVALID_PRICE_MODIFIER) { if (price_base_multipliers[p] == INVALID_PRICE_MODIFIER) {
/* No multiplier was set; set it to a neutral value */ /* No multiplier was set; set it to a neutral value */
price_base_multipliers[p] = 0; price_base_multipliers[p] = 0;
} else { } 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, /* The grf does not define any objects of the feature,
* so it must be a difficulty setting. Apply it globally */ * 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]); SetPriceBaseMultiplier(p, price_base_multipliers[p]);
price_base_multipliers[p] = 0; price_base_multipliers[p] = 0;
} else { } 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 */ /** Finish loading NewGRFs and execute needed post-processing */
static void AfterLoadGRFs() static void AfterLoadGRFs()
{ {
for (StringIDMapping *it = _string_to_grf_mapping.Begin(); it != _string_to_grf_mapping.End(); it++) { for (StringIDMapping &it : _string_to_grf_mapping) {
*it->target = MapGRFStringID(it->grfid, it->source); *it.target = MapGRFStringID(it.grfid, it.source);
} }
_string_to_grf_mapping.clear(); _string_to_grf_mapping.clear();

@ -683,7 +683,7 @@ uint32 NewGRFSpriteLayout::PrepareLayout(uint32 orig_offset, uint32 newgrf_groun
* and apply the default sprite offsets (unless disabled). */ * and apply the default sprite offsets (unless disabled). */
const TileLayoutRegisters *regs = this->registers; const TileLayoutRegisters *regs = this->registers;
bool ground = true; bool ground = true;
foreach_draw_tile_seq(result, result_seq.Begin()) { foreach_draw_tile_seq(result, result_seq.data()) {
TileLayoutFlags flags = TLF_NOTHING; TileLayoutFlags flags = TLF_NOTHING;
if (regs != NULL) flags = regs->flags; if (regs != NULL) flags = regs->flags;
@ -737,7 +737,7 @@ void NewGRFSpriteLayout::ProcessRegisters(uint8 resolved_var10, uint32 resolved_
DrawTileSeqStruct *result; DrawTileSeqStruct *result;
const TileLayoutRegisters *regs = this->registers; const TileLayoutRegisters *regs = this->registers;
bool ground = true; bool ground = true;
foreach_draw_tile_seq(result, result_seq.Begin()) { foreach_draw_tile_seq(result, result_seq.data()) {
TileLayoutFlags flags = TLF_NOTHING; TileLayoutFlags flags = TLF_NOTHING;
if (regs != NULL) flags = regs->flags; if (regs != NULL) flags = regs->flags;

@ -164,7 +164,7 @@ struct NewGRFSpriteLayout : ZeroedMemoryAllocator, DrawTileSprites {
*/ */
const DrawTileSeqStruct *GetLayout(PalSpriteID *ground) const const DrawTileSeqStruct *GetLayout(PalSpriteID *ground) const
{ {
DrawTileSeqStruct *front = result_seq.Begin(); DrawTileSeqStruct *front = result_seq.data();
*ground = front->image; *ground = front->image;
return front + 1; return front + 1;
} }

@ -182,9 +182,9 @@ void GRFConfig::SetSuitablePalette()
*/ */
void GRFConfig::FinalizeParameterInfo() void GRFConfig::FinalizeParameterInfo()
{ {
for (GRFParameterInfo **info = this->param_info.Begin(); info != this->param_info.End(); ++info) { for (GRFParameterInfo *info : this->param_info) {
if (*info == NULL) continue; if (info == NULL) continue;
(*info)->Finalize(); info->Finalize();
} }
} }

@ -840,8 +840,8 @@ struct SpriteAlignerWindow : Window {
/* Relative offset is new absolute offset - starting absolute offset. /* 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). * Show 0, 0 as the relative offsets if entry is not in the map (meaning they have not been changed yet).
*/ */
const SmallPair<SpriteID, XyOffs> *key_offs_pair = this->offs_start_map.Find(this->current_sprite); const auto key_offs_pair = this->offs_start_map.Find(this->current_sprite);
if (key_offs_pair != this->offs_start_map.End()) { if (key_offs_pair != this->offs_start_map.end()) {
SetDParam(0, spr->x_offs - key_offs_pair->second.first); SetDParam(0, spr->x_offs - key_offs_pair->second.first);
SetDParam(1, spr->y_offs - key_offs_pair->second.second); SetDParam(1, spr->y_offs - key_offs_pair->second.second);
} else { } else {

@ -1231,13 +1231,12 @@ void CommitVehicleListOrderChanges()
FOR_ALL_ENGINES(e) { FOR_ALL_ENGINES(e) {
ordering.push_back(e->index); ordering.push_back(e->index);
} }
QSortT(ordering.Begin(), ordering.size(), EnginePreSort); QSortT(ordering.data(), ordering.size(), EnginePreSort);
/* Apply Insertion-Sort operations */ /* Apply Insertion-Sort operations */
const ListOrderChange *end = _list_order_changes.End(); for (const ListOrderChange &it : _list_order_changes) {
for (const ListOrderChange *it = _list_order_changes.Begin(); it != end; ++it) { EngineID source = it.engine;
EngineID source = it->engine; uint local_target = it.target;
uint local_target = it->target;
const EngineIDMapping *id_source = _engine_mngr.data() + source; const EngineIDMapping *id_source = _engine_mngr.data() + source;
if (id_source->internal_id == local_target) continue; if (id_source->internal_id == local_target) continue;
@ -1251,7 +1250,7 @@ void CommitVehicleListOrderChanges()
assert(source_index >= 0 && target_index >= 0); assert(source_index >= 0 && target_index >= 0);
assert(source_index != target_index); assert(source_index != target_index);
EngineID *list = ordering.Begin(); EngineID *list = ordering.data();
if (source_index < target_index) { if (source_index < target_index) {
--target_index; --target_index;
for (int i = source_index; i < target_index; ++i) list[i] = list[i + 1]; for (int i = source_index; i < target_index; ++i) list[i] = list[i + 1];
@ -1263,10 +1262,10 @@ void CommitVehicleListOrderChanges()
} }
/* Store final sort-order */ /* Store final sort-order */
const EngineID *idend = ordering.End();
uint index = 0; uint index = 0;
for (const EngineID *it = ordering.Begin(); it != idend; ++it, ++index) { for (const EngineID &eid : ordering) {
Engine::Get(*it)->list_position = index; Engine::Get(eid)->list_position = index;
++index;
} }
/* Clear out the queue */ /* Clear out the queue */

@ -168,8 +168,8 @@ static byte _currentLangID = GRFLX_ENGLISH; ///< by default, english is used.
int LanguageMap::GetMapping(int newgrf_id, bool gender) const int LanguageMap::GetMapping(int newgrf_id, bool gender) const
{ {
const SmallVector<Mapping, 1> &map = gender ? this->gender_map : this->case_map; const SmallVector<Mapping, 1> &map = gender ? this->gender_map : this->case_map;
for (const Mapping *m = map.Begin(); m != map.End(); m++) { for (const Mapping &m : map) {
if (m->newgrf_id == newgrf_id) return m->openttd_id; if (m.newgrf_id == newgrf_id) return m.openttd_id;
} }
return -1; return -1;
} }
@ -183,8 +183,8 @@ int LanguageMap::GetMapping(int newgrf_id, bool gender) const
int LanguageMap::GetReverseMapping(int openttd_id, bool gender) const int LanguageMap::GetReverseMapping(int openttd_id, bool gender) const
{ {
const SmallVector<Mapping, 1> &map = gender ? this->gender_map : this->case_map; const SmallVector<Mapping, 1> &map = gender ? this->gender_map : this->case_map;
for (const Mapping *m = map.Begin(); m != map.End(); m++) { for (const Mapping &m : map) {
if (m->openttd_id == openttd_id) return m->newgrf_id; if (m.openttd_id == openttd_id) return m.newgrf_id;
} }
return -1; return -1;
} }
@ -194,8 +194,8 @@ struct UnmappedChoiceList : ZeroedMemoryAllocator {
/** Clean everything up. */ /** Clean everything up. */
~UnmappedChoiceList() ~UnmappedChoiceList()
{ {
for (SmallPair<byte, char *> *p = this->strings.Begin(); p < this->strings.End(); p++) { for (SmallPair<byte, char *> p : this->strings) {
free(p->second); free(p.second);
} }
} }

@ -453,9 +453,8 @@ ClearedObjectArea *FindClearedObject(TileIndex tile)
{ {
TileArea ta = TileArea(tile, 1, 1); TileArea ta = TileArea(tile, 1, 1);
const ClearedObjectArea *end = _cleared_object_areas.End(); for (ClearedObjectArea &coa : _cleared_object_areas) {
for (ClearedObjectArea *coa = _cleared_object_areas.Begin(); coa != end; coa++) { if (coa.area.Intersects(ta)) return &coa;
if (coa->area.Intersects(ta)) return coa;
} }
return NULL; return NULL;

@ -75,8 +75,8 @@ public:
/* Extract font information for this run. */ /* Extract font information for this run. */
CFRange chars = CTRunGetStringRange(run); CFRange chars = CTRunGetStringRange(run);
FontMap::const_iterator map = fontMapping.Begin(); auto map = fontMapping.begin();
while (map < fontMapping.End() - 1 && map->first <= chars.location) map++; while (map < fontMapping.end() - 1 && map->first <= chars.location) map++;
this->push_back(new CoreTextVisualRun(run, map->second, buff)); this->push_back(new CoreTextVisualRun(run, map->second, buff));
} }
@ -137,8 +137,8 @@ static CTRunDelegateCallbacks _sprite_font_callback = {
if (length == 0) return NULL; if (length == 0) return NULL;
/* Can't layout our in-built sprite fonts. */ /* Can't layout our in-built sprite fonts. */
for (FontMap::const_iterator i = fontMapping.Begin(); i != fontMapping.End(); i++) { for (const auto &i : fontMapping) {
if (i->second->fc->IsBuiltInFont()) return NULL; if (i.second->fc->IsBuiltInFont()) return NULL;
} }
/* Make attributed string with embedded font information. */ /* 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 /* Apply font and colour ranges to our string. This is important to make sure
* that we get proper glyph boundaries on style changes. */ * that we get proper glyph boundaries on style changes. */
int last = 0; int last = 0;
for (FontMap::const_iterator i = fontMapping.Begin(); i != fontMapping.End(); i++) { for (const auto &i : fontMapping) {
if (i->first - last == 0) continue; 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. */ /* Cache font information. */
CFStringRef font_name = CFStringCreateWithCString(kCFAllocatorDefault, i->second->fc->GetFontName(), kCFStringEncodingUTF8); CFStringRef font_name = CFStringCreateWithCString(kCFAllocatorDefault, i.second->fc->GetFontName(), kCFStringEncodingUTF8);
_font_cache[i->second->fc->GetSize()] = CTFontCreateWithName(font_name, i->second->fc->GetFontSize(), NULL); _font_cache[i.second->fc->GetSize()] = CTFontCreateWithName(font_name, i.second->fc->GetFontSize(), NULL);
CFRelease(font_name); 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. 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); CFAttributedStringSetAttribute(str, CFRangeMake(last, i.first - last), kCTForegroundColorAttributeName, color);
CGColorRelease(color); CGColorRelease(color);
/* Install a size callback for our special sprite glyphs. */ /* 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) { 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); CFAttributedStringSetAttribute(str, CFRangeMake(c, 1), kCTRunDelegateAttributeName, del);
CFRelease(del); CFRelease(del);
} }
} }
last = i->first; last = i.first;
} }
CFAttributedStringEndEditing(str); CFAttributedStringEndEditing(str);
@ -243,8 +243,8 @@ CoreTextParagraphLayout::CoreTextVisualRun::CoreTextVisualRun(CTRunRef run, Font
int CoreTextParagraphLayout::CoreTextLine::GetLeading() const int CoreTextParagraphLayout::CoreTextLine::GetLeading() const
{ {
int leading = 0; int leading = 0;
for (const CoreTextVisualRun * const *run = this->Begin(); run != this->End(); run++) { for (const CoreTextVisualRun * const &run : *this) {
leading = max(leading, (*run)->GetLeading()); leading = max(leading, run->GetLeading());
} }
return leading; return leading;
@ -259,8 +259,8 @@ int CoreTextParagraphLayout::CoreTextLine::GetWidth() const
if (this->size() == 0) return 0; if (this->size() == 0) return 0;
int total_width = 0; int total_width = 0;
for (const CoreTextVisualRun * const *run = this->Begin(); run != this->End(); run++) { for (const CoreTextVisualRun * const &run : *this) {
total_width += (*run)->GetAdvance(); total_width += run->GetAdvance();
} }
return total_width; return total_width;

@ -282,8 +282,8 @@ static std::vector<SCRIPT_ITEM> UniscribeItemizeString(UniscribeParagraphLayoutF
if (length == 0) return NULL; if (length == 0) return NULL;
/* Can't layout our in-built sprite fonts. */ /* Can't layout our in-built sprite fonts. */
for (FontMap::const_iterator i = fontMapping.Begin(); i != fontMapping.End(); i++) { for (auto const &pair : fontMapping) {
if (i->second->fc->IsBuiltInFont()) return NULL; if (pair.second->fc->IsBuiltInFont()) return NULL;
} }
/* Itemize text. */ /* Itemize text. */
@ -296,12 +296,12 @@ static std::vector<SCRIPT_ITEM> UniscribeItemizeString(UniscribeParagraphLayoutF
int cur_pos = 0; int cur_pos = 0;
std::vector<SCRIPT_ITEM>::iterator cur_item = items.begin(); std::vector<SCRIPT_ITEM>::iterator cur_item = items.begin();
for (FontMap::const_iterator i = fontMapping.Begin(); i != fontMapping.End(); i++) { for (auto const &i : fontMapping) {
while (cur_pos < i->first && cur_item != items.end() - 1) { while (cur_pos < i.first && cur_item != items.end() - 1) {
/* Add a range that spans the intersection of the remaining item and font run. */ /* 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); 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. */ /* Shape the range. */
if (!UniscribeShapeRun(buff, ranges.back())) { if (!UniscribeShapeRun(buff, ranges.back())) {
@ -448,8 +448,8 @@ static std::vector<SCRIPT_ITEM> UniscribeItemizeString(UniscribeParagraphLayoutF
int UniscribeParagraphLayout::UniscribeLine::GetLeading() const int UniscribeParagraphLayout::UniscribeLine::GetLeading() const
{ {
int leading = 0; int leading = 0;
for (const UniscribeVisualRun * const *run = this->Begin(); run != this->End(); run++) { for (const UniscribeVisualRun *run : *this) {
leading = max(leading, (*run)->GetLeading()); leading = max(leading, run->GetLeading());
} }
return leading; return leading;
@ -462,8 +462,8 @@ int UniscribeParagraphLayout::UniscribeLine::GetLeading() const
int UniscribeParagraphLayout::UniscribeLine::GetWidth() const int UniscribeParagraphLayout::UniscribeLine::GetWidth() const
{ {
int length = 0; int length = 0;
for (const UniscribeVisualRun * const *run = this->Begin(); run != this->End(); run++) { for (const UniscribeVisualRun *run : *this) {
length += (*run)->GetAdvance(); length += run->GetAdvance();
} }
return length; return length;

@ -1754,8 +1754,8 @@ CommandCost CmdConvertRail(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3
if (flags & DC_EXEC) { if (flags & DC_EXEC) {
/* Railtype changed, update trains as when entering different track */ /* Railtype changed, update trains as when entering different track */
for (Train **v = affected_trains.Begin(); v != affected_trains.End(); v++) { for (Train *v : affected_trains) {
(*v)->ConsistChanged(CCF_TRACK); v->ConsistChanged(CCF_TRACK);
} }
} }

@ -2197,12 +2197,12 @@ bool AfterLoadGame()
extern SmallVector<TileIndex, 256> _animated_tiles; extern SmallVector<TileIndex, 256> _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 */ /* Remove if tile is not animated */
bool remove = _tile_type_procs[GetTileType(*tile)]->animate_tile_proc == NULL; bool remove = _tile_type_procs[GetTileType(*tile)]->animate_tile_proc == NULL;
/* and remove if duplicate */ /* 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; remove = *tile == *j;
} }
@ -2981,9 +2981,12 @@ bool AfterLoadGame()
while (cur_skip > skip_frames[0]) { while (cur_skip > skip_frames[0]) {
RoadVehicle *u = v; RoadVehicle *u = v;
RoadVehicle *prev = NULL; 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); 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--; cur_skip--;
} }

@ -25,8 +25,8 @@ extern SmallVector<TileIndex, 256> _animated_tiles;
*/ */
static void Save_ANIT() static void Save_ANIT()
{ {
SlSetLength(_animated_tiles.size() * sizeof(*_animated_tiles.Begin())); SlSetLength(_animated_tiles.size() * sizeof(_animated_tiles.front()));
SlArray(_animated_tiles.Begin(), _animated_tiles.size(), SLE_UINT32); SlArray(_animated_tiles.data(), _animated_tiles.size(), SLE_UINT32);
} }
/** /**
@ -47,10 +47,10 @@ static void Load_ANIT()
return; return;
} }
uint count = (uint)SlGetFieldLength() / sizeof(*_animated_tiles.Begin()); uint count = (uint)SlGetFieldLength() / sizeof(_animated_tiles.front());
_animated_tiles.clear(); _animated_tiles.clear();
_animated_tiles.resize(_animated_tiles.size() + count); _animated_tiles.resize(_animated_tiles.size() + count);
SlArray(_animated_tiles.Begin(), count, SLE_UINT32); SlArray(_animated_tiles.data(), count, SLE_UINT32);
} }
/** /**

@ -177,11 +177,11 @@ static const SaveLoad _engine_id_mapping_desc[] = {
static void Save_EIDS() static void Save_EIDS()
{ {
const EngineIDMapping *end = _engine_mngr.End();
uint index = 0; uint index = 0;
for (EngineIDMapping *eid = _engine_mngr.Begin(); eid != end; eid++, index++) { for (EngineIDMapping &eid : _engine_mngr) {
SlSetArrayIndex(index); SlSetArrayIndex(index);
SlObject(eid, _engine_id_mapping_desc); SlObject(&eid, _engine_id_mapping_desc);
index++;
} }
} }

@ -52,10 +52,10 @@ static void UpdateWaypointOrder(Order *o)
{ {
if (!o->IsType(OT_GOTO_WAYPOINT)) return; if (!o->IsType(OT_GOTO_WAYPOINT)) return;
for (OldWaypoint *wp = _old_waypoints.Begin(); wp != _old_waypoints.End(); wp++) { for (OldWaypoint &wp : _old_waypoints) {
if (wp->index != o->GetDestination()) continue; if (wp.index != o->GetDestination()) continue;
o->SetDestination((DestinationID)wp->new_index); o->SetDestination((DestinationID)wp.new_index);
return; return;
} }
} }
@ -71,25 +71,25 @@ void MoveWaypointsToBaseStations()
* id which was stored in m4 is now saved as a grf/id reference in the * id which was stored in m4 is now saved as a grf/id reference in the
* waypoint struct. */ * waypoint struct. */
if (IsSavegameVersionBefore(SLV_17)) { if (IsSavegameVersionBefore(SLV_17)) {
for (OldWaypoint *wp = _old_waypoints.Begin(); wp != _old_waypoints.End(); wp++) { for (OldWaypoint &wp : _old_waypoints) {
if (wp->delete_ctr != 0) continue; // The waypoint was deleted if (wp.delete_ctr != 0) continue; // The waypoint was deleted
/* Waypoint indices were not added to the map prior to this. */ /* 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)) { if (HasBit(_m[wp.xy].m3, 4)) {
wp->spec = StationClass::Get(STAT_CLASS_WAYP)->GetSpec(_m[wp->xy].m4 + 1); wp.spec = StationClass::Get(STAT_CLASS_WAYP)->GetSpec(_m[wp.xy].m4 + 1);
} }
} }
} else { } else {
/* As of version 17, we recalculate the custom graphic ID of waypoints /* As of version 17, we recalculate the custom graphic ID of waypoints
* from the GRF ID / station index. */ * 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); StationClass* stclass = StationClass::Get(STAT_CLASS_WAYP);
for (uint i = 0; i < stclass->GetSpecCount(); i++) { for (uint i = 0; i < stclass->GetSpecCount(); i++) {
const StationSpec *statspec = stclass->GetSpec(i); const StationSpec *statspec = stclass->GetSpec(i);
if (statspec != NULL && statspec->grf_prop.grffile->grfid == wp->grfid && statspec->grf_prop.local_id == wp->localidx) { if (statspec != NULL && statspec->grf_prop.grffile->grfid == wp.grfid && statspec->grf_prop.local_id == wp.localidx) {
wp->spec = statspec; wp.spec = statspec;
break; break;
} }
} }
@ -99,19 +99,19 @@ void MoveWaypointsToBaseStations()
if (!Waypoint::CanAllocateItem(_old_waypoints.size())) SlError(STR_ERROR_TOO_MANY_STATIONS_LOADING); if (!Waypoint::CanAllocateItem(_old_waypoints.size())) SlError(STR_ERROR_TOO_MANY_STATIONS_LOADING);
/* All saveload conversions have been done. Create the new waypoints! */ /* All saveload conversions have been done. Create the new waypoints! */
for (OldWaypoint *wp = _old_waypoints.Begin(); wp != _old_waypoints.End(); wp++) { for (OldWaypoint &wp : _old_waypoints) {
Waypoint *new_wp = new Waypoint(wp->xy); Waypoint *new_wp = new Waypoint(wp.xy);
new_wp->town = wp->town; new_wp->town = wp.town;
new_wp->town_cn = wp->town_cn; new_wp->town_cn = wp.town_cn;
new_wp->name = wp->name; new_wp->name = wp.name;
new_wp->delete_ctr = 0; // Just reset delete counter for once. new_wp->delete_ctr = 0; // Just reset delete counter for once.
new_wp->build_date = wp->build_date; new_wp->build_date = wp.build_date;
new_wp->owner = wp->owner; new_wp->owner = wp.owner;
new_wp->string_id = STR_SV_STNAME_WAYPOINT; new_wp->string_id = STR_SV_STNAME_WAYPOINT;
TileIndex t = wp->xy; TileIndex t = wp.xy;
if (IsTileType(t, MP_RAILWAY) && GetRailTileType(t) == 2 /* RAIL_TILE_WAYPOINT */ && _m[t].m2 == wp->index) { if (IsTileType(t, MP_RAILWAY) && GetRailTileType(t) == 2 /* RAIL_TILE_WAYPOINT */ && _m[t].m2 == wp.index) {
/* The tile might've been reserved! */ /* The tile might've been reserved! */
bool reserved = !IsSavegameVersionBefore(SLV_100) && HasBit(_m[t].m5, 4); bool reserved = !IsSavegameVersionBefore(SLV_100) && HasBit(_m[t].m5, 4);
@ -122,13 +122,13 @@ void MoveWaypointsToBaseStations()
SetRailStationReservation(t, reserved); SetRailStationReservation(t, reserved);
if (wp->spec != NULL) { if (wp.spec != NULL) {
SetCustomStationSpecIndex(t, AllocateSpecToStation(wp->spec, new_wp, true)); SetCustomStationSpecIndex(t, AllocateSpecToStation(wp.spec, new_wp, true));
} }
new_wp->rect.BeforeAddTile(t, StationRect::ADD_FORCE); 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 */ /* Update the orders of vehicles */
@ -189,15 +189,15 @@ static void Load_WAYP()
static void Ptrs_WAYP() static void Ptrs_WAYP()
{ {
for (OldWaypoint *wp = _old_waypoints.Begin(); wp != _old_waypoints.End(); wp++) { for (OldWaypoint &wp : _old_waypoints) {
SlObject(wp, _old_waypoint_desc); SlObject(&wp, _old_waypoint_desc);
if (IsSavegameVersionBefore(SLV_12)) { if (IsSavegameVersionBefore(SLV_12)) {
wp->town_cn = (wp->string_id & 0xC000) == 0xC000 ? (wp->string_id >> 8) & 0x3F : 0; wp.town_cn = (wp.string_id & 0xC000) == 0xC000 ? (wp.string_id >> 8) & 0x3F : 0;
wp->town = ClosestTownFromTile(wp->xy, UINT_MAX); wp.town = ClosestTownFromTile(wp.xy, UINT_MAX);
} else if (IsSavegameVersionBefore(SLV_122)) { } else if (IsSavegameVersionBefore(SLV_122)) {
/* Only for versions 12 .. 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 /* 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 * 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 * 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(); _old_waypoints.clear();
SlErrorCorrupt("Referencing invalid Town"); SlErrorCorrupt("Referencing invalid Town");
} }
wp->town = Town::Get(wp->town_index); wp.town = Town::Get(wp.town_index);
} }
if (IsSavegameVersionBefore(SLV_84)) { if (IsSavegameVersionBefore(SLV_84)) {
wp->name = CopyFromOldName(wp->string_id); wp.name = CopyFromOldName(wp.string_id);
} }
} }
} }

@ -26,8 +26,8 @@ ScriptInfo::~ScriptInfo()
free((*it).name); free((*it).name);
free((*it).description); free((*it).description);
if (it->labels != NULL) { if (it->labels != NULL) {
for (LabelMapping::iterator it2 = (*it).labels->Begin(); it2 != (*it).labels->End(); it2++) { for (auto &lbl_map : *(*it).labels) {
free(it2->second); free(lbl_map.second);
} }
delete it->labels; delete it->labels;
} }

@ -149,7 +149,7 @@ namespace SQConvert {
Array *arr = (Array*)MallocT<byte>(sizeof(Array) + sizeof(int32) * data.size()); Array *arr = (Array*)MallocT<byte>(sizeof(Array) + sizeof(int32) * data.size());
arr->size = 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); ptr->push_back(arr);
return arr; return arr;

@ -747,8 +747,8 @@ static void IniSaveSettingList(IniFile *ini, const char *grpname, StringList *li
if (group == NULL || list == NULL) return; if (group == NULL || list == NULL) return;
group->Clear(); group->Clear();
for (char **iter = list->Begin(); iter != list->End(); iter++) { for (char *iter : *list) {
group->GetItem(*iter, true)->SetValue(""); group->GetItem(iter, true)->SetValue("");
} }
} }

@ -215,7 +215,7 @@ struct GameOptionsWindow : Window {
if (i == CURRENCY_CUSTOM) continue; if (i == CURRENCY_CUSTOM) continue;
list->push_back(new DropDownListStringItem(*items, i, HasBit(disabled, i))); 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 */ /* Append custom currency at the end */
list->push_back(new DropDownListItem(-1, false)); // separator line list->push_back(new DropDownListItem(-1, false)); // separator line
@ -253,7 +253,7 @@ struct GameOptionsWindow : Window {
int result = _nb_orig_names + i; int result = _nb_orig_names + i;
list->push_back(new DropDownListStringItem(_grf_names[i], result, enabled_item != result && enabled_item >= 0)); 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(); int newgrf_size = list->size();
/* Insert newgrf_names at the top of the list */ /* 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++) { 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)); 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; break;
} }
@ -286,7 +286,7 @@ struct GameOptionsWindow : Window {
if (&_languages[i] == _current_language) *selected_index = i; if (&_languages[i] == _current_language) *selected_index = i;
list->push_back(new DropDownListStringItem(SPECSTR_LANGUAGE_START + i, i, false)); 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; break;
} }
@ -432,11 +432,11 @@ struct GameOptionsWindow : Window {
DropDownList *list = this->BuildDropDownList(widget, &selected); DropDownList *list = this->BuildDropDownList(widget, &selected);
if (list != NULL) { if (list != NULL) {
/* Find the biggest item for the default size. */ /* 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; Dimension string_dim;
int width = (*it)->Width(); int width = ddli->Width();
string_dim.width = width + padding.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); *size = maxdim(*size, string_dim);
} }
delete list; delete list;

@ -136,8 +136,8 @@ public:
*/ */
void Write(FILE *out_fp) const void Write(FILE *out_fp) const
{ {
for (const OutputBuffer *out_data = this->output_buffer.Begin(); out_data != this->output_buffer.End(); out_data++) { for (const OutputBuffer &out_data : output_buffer) {
out_data->Write(out_fp); out_data.Write(out_fp);
} }
} }

@ -1622,8 +1622,7 @@ CommandCost RemoveFromRailBaseStation(TileArea ta, SmallVector<T *, 4> &affected
if (quantity == 0) return error.Failed() ? error : CommandCost(STR_ERROR_THERE_IS_NO_STATION); 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++) { for (T *st : affected_stations) {
T *st = *stp;
/* now we need to make the "spanned" area of the railway station smaller /* now we need to make the "spanned" area of the railway station smaller
* if we deleted something at the edges. * if we deleted something at the edges.
@ -1667,8 +1666,7 @@ CommandCost CmdRemoveFromRailStation(TileIndex start, DoCommandFlag flags, uint3
if (ret.Failed()) return ret; if (ret.Failed()) return ret;
/* Do all station specific functions here. */ /* Do all station specific functions here. */
for (Station **stp = affected_stations.Begin(); stp != affected_stations.End(); stp++) { for (Station *st : affected_stations) {
Station *st = *stp;
if (st->train_station.tile == INVALID_TILE) SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS); if (st->train_station.tile == INVALID_TILE) SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
st->MarkTilesDirty(false); st->MarkTilesDirty(false);

@ -130,8 +130,7 @@ protected:
int GetSelPageNum() const int GetSelPageNum() const
{ {
int page_number = 0; int page_number = 0;
for (const StoryPage *const*iter = this->story_pages.Begin(); iter != this->story_pages.End(); iter++) { for (const StoryPage *p : this->story_pages) {
const StoryPage *p = *iter;
if (p->index == this->selected_page_id) { if (p->index == this->selected_page_id) {
return page_number; return page_number;
} }
@ -148,7 +147,7 @@ protected:
/* Verify that the selected page exist. */ /* Verify that the selected page exist. */
if (!_story_page_pool.IsValidID(this->selected_page_id)) return false; 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 (!_story_page_pool.IsValidID(this->selected_page_id)) return false;
if (this->story_pages.size() <= 1) return true; 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; 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. */ /* Find the last available page which is previous to the current selected page. */
const StoryPage *last_available; const StoryPage *last_available;
last_available = NULL; last_available = NULL;
for (const StoryPage *const*iter = this->story_pages.Begin(); iter != this->story_pages.End(); iter++) { for (const StoryPage *p : this->story_pages) {
const StoryPage *p = *iter;
if (p->index == this->selected_page_id) { if (p->index == this->selected_page_id) {
if (last_available == NULL) return; // No previous page available. if (last_available == NULL) return; // No previous page available.
this->SetSelectedPage(last_available->index); this->SetSelectedPage(last_available->index);
@ -214,12 +212,12 @@ protected:
if (!_story_page_pool.IsValidID(this->selected_page_id)) return; if (!_story_page_pool.IsValidID(this->selected_page_id)) return;
/* Find selected page. */ /* 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; const StoryPage *p = *iter;
if (p->index == this->selected_page_id) { if (p->index == this->selected_page_id) {
/* Select the page after selected page. */ /* Select the page after selected page. */
iter++; iter++;
if (iter != this->story_pages.End()) { if (iter != this->story_pages.end()) {
this->SetSelectedPage((*iter)->index); this->SetSelectedPage((*iter)->index);
} }
return; return;
@ -234,8 +232,7 @@ protected:
{ {
DropDownList *list = new DropDownList(); DropDownList *list = new DropDownList();
uint16 page_num = 1; uint16 page_num = 1;
for (const StoryPage *const*iter = this->story_pages.Begin(); iter != this->story_pages.End(); iter++) { for (const StoryPage *p : this->story_pages) {
const StoryPage *p = *iter;
bool current_page = p->index == this->selected_page_id; bool current_page = p->index == this->selected_page_id;
DropDownListStringItem *item = NULL; DropDownListStringItem *item = NULL;
if (p->title != NULL) { if (p->title != NULL) {
@ -353,8 +350,7 @@ protected:
uint height = GetHeadHeight(max_width); uint height = GetHeadHeight(max_width);
/* Body */ /* Body */
for (const StoryPageElement **iter = this->story_page_elements.Begin(); iter != this->story_page_elements.End(); iter++) { for (const StoryPageElement *pe : this->story_page_elements) {
const StoryPageElement *pe = *iter;
height += element_vertical_dist; height += element_vertical_dist;
height += GetPageElementHeight(*pe, max_width); 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); y_offset = DrawStringMultiLine(0, right - x, y_offset, bottom - y, STR_STORY_BOOK_TITLE, TC_BLACK, SA_TOP | SA_HOR_CENTER);
/* Page elements */ /* Page elements */
for (const StoryPageElement *const*iter = this->story_page_elements.Begin(); iter != this->story_page_elements.End(); iter++) { for (const StoryPageElement *const pe : this->story_page_elements) {
const StoryPageElement *const pe = *iter;
y_offset += line_height; // margin to previous element y_offset += line_height; // margin to previous element
switch (pe->type) { switch (pe->type) {
@ -650,8 +645,7 @@ public:
/* Detect if a page element was clicked. */ /* Detect if a page element was clicked. */
uint y = head_height; uint y = head_height;
uint element_vertical_dist = FONT_HEIGHT_NORMAL; uint element_vertical_dist = FONT_HEIGHT_NORMAL;
for (const StoryPageElement *const*iter = this->story_page_elements.Begin(); iter != this->story_page_elements.End(); iter++) { for (const StoryPageElement *const pe : this->story_page_elements) {
const StoryPageElement *const pe = *iter;
y += element_vertical_dist; // margin row y += element_vertical_dist; // margin row

@ -1045,7 +1045,7 @@ void LanguageWriter::WriteLang(const StringData &data)
if (cmdp != NULL) PutCommandString(&buffer, cmdp); if (cmdp != NULL) PutCommandString(&buffer, cmdp);
this->WriteLength(buffer.size()); this->WriteLength(buffer.size());
this->Write(buffer.Begin(), buffer.size()); this->Write(buffer.data(), buffer.size());
buffer.clear(); buffer.clear();
} }
} }

@ -674,7 +674,7 @@ public:
UText text = UTEXT_INITIALIZER; UText text = UTEXT_INITIALIZER;
UErrorCode status = U_ZERO_ERROR; 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->char_itr->setText(&text, status);
this->word_itr->setText(&text, status); this->word_itr->setText(&text, status);
this->char_itr->first(); this->char_itr->first();

@ -91,9 +91,8 @@ void StringFilter::SetFilterTerm(const char *str)
void StringFilter::ResetState() void StringFilter::ResetState()
{ {
this->word_matches = 0; this->word_matches = 0;
const WordState *end = this->word_index.End(); for (WordState &ws : this->word_index) {
for (WordState *it = this->word_index.Begin(); it != end; ++it) { ws.match = false;
it->match = false;
} }
} }
@ -110,11 +109,10 @@ void StringFilter::AddLine(const char *str)
if (str == NULL) return; if (str == NULL) return;
bool match_case = this->case_sensitive != NULL && *this->case_sensitive; bool match_case = this->case_sensitive != NULL && *this->case_sensitive;
const WordState *end = this->word_index.End(); for (WordState &ws : this->word_index) {
for (WordState *it = this->word_index.Begin(); it != end; ++it) { if (!ws.match) {
if (!it->match) { if ((match_case ? strstr(str, ws.start) : strcasestr(str, ws.start)) != NULL) {
if ((match_case ? strstr(str, it->start) : strcasestr(str, it->start)) != NULL) { ws.match = true;
it->match = true;
this->word_matches++; this->word_matches++;
} }
} }

@ -1876,8 +1876,8 @@ int CDECL StringIDSorter(const StringID *a, const StringID *b)
*/ */
const LanguageMetadata *GetLanguage(byte newgrflangid) const LanguageMetadata *GetLanguage(byte newgrflangid)
{ {
for (const LanguageMetadata *lang = _languages.Begin(); lang != _languages.End(); lang++) { for (const LanguageMetadata &lang : _languages) {
if (newgrflangid == lang->newgrflangid) return lang; if (newgrflangid == lang.newgrflangid) return &lang;
} }
return NULL; 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 *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 *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. */ /* 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 /* We are trying to find a default language. The priority is by
* configuration file, local environment and last, if nothing found, * configuration file, local environment and last, if nothing found,
* English. */ * 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) { if (strcmp(lang_file, _config_language_file) == 0) {
chosen_language = lng; chosen_language = &lng;
break; break;
} }
if (strcmp (lng->isocode, "en_GB") == 0) en_GB_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, 5) == 0) chosen_language = &lng;
if (strncmp(lng->isocode, lang, 2) == 0) language_fallback = 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. /* We haven't found the language in the config nor the one in the locale.

@ -601,9 +601,9 @@ bool CheckSubsidised(CargoID cargo_type, CompanyID company, SourceType src_type,
} }
break; break;
case ST_TOWN: case ST_TOWN:
for (const Town * const *tp = towns_near.Begin(); tp != towns_near.End(); tp++) { for (const Town *tp : towns_near) {
if (s->dst == (*tp)->index) { if (s->dst == tp->index) {
assert((*tp)->cache.part_of_subsidy & POS_DST); assert(tp->cache.part_of_subsidy & POS_DST);
subsidised = true; subsidised = true;
if (!s->IsAwarded()) s->AwardTo(company); if (!s->IsAwarded()) s->AwardTo(company);
} }

@ -89,20 +89,19 @@ void MoveAllTextEffects(uint delta_ms)
uint count = texteffecttimer.CountElapsed(delta_ms); uint count = texteffecttimer.CountElapsed(delta_ms);
if (count == 0) return; if (count == 0) return;
const TextEffect *end = _text_effects.End(); for (TextEffect &te : _text_effects) {
for (TextEffect *te = _text_effects.Begin(); te != end; te++) { if (te.string_id == INVALID_STRING_ID) continue;
if (te->string_id == INVALID_STRING_ID) continue; if (te.mode != TE_RISING) continue;
if (te->mode != TE_RISING) continue;
if (te->duration < count) { if (te.duration < count) {
te->Reset(); te.Reset();
continue; continue;
} }
te->MarkDirty(ZOOM_LVL_OUT_8X); te.MarkDirty(ZOOM_LVL_OUT_8X);
te->duration -= count; te.duration -= count;
te->top -= count * ZOOM_LVL_BASE; te.top -= count * ZOOM_LVL_BASE;
te->MarkDirty(ZOOM_LVL_OUT_8X); 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 */ /* Don't draw the text effects when zoomed out a lot */
if (dpi->zoom > ZOOM_LVL_OUT_8X) return; if (dpi->zoom > ZOOM_LVL_OUT_8X) return;
const TextEffect *end = _text_effects.End(); for (TextEffect &te : _text_effects) {
for (TextEffect *te = _text_effects.Begin(); te != end; te++) { if (te.string_id == INVALID_STRING_ID) continue;
if (te->string_id == INVALID_STRING_ID) continue; if (te.mode == TE_RISING || (_settings_client.gui.loading_indicators && !IsTransparencySet(TO_LOADING))) {
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);
ViewportAddString(dpi, ZOOM_LVL_OUT_8X, te, te->string_id, te->string_id - 1, STR_NULL, te->params_1, te->params_2);
} }
} }
} }

@ -295,13 +295,12 @@ CommandCost CmdSetTimetableStart(TileIndex tile, DoCommandFlag flags, uint32 p1,
int num_vehs = vehs.size(); int num_vehs = vehs.size();
if (num_vehs >= 2) { 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); int idx = vehs.begin() - std::find(vehs.begin(), vehs.end(), v);
for (Vehicle **viter = vehs.Begin(); viter != vehs.End(); viter++) { for (Vehicle *w : vehs) {
Vehicle *w = *viter;
w->lateness_counter = 0; w->lateness_counter = 0;
ClrBit(w->vehicle_flags, VF_TIMETABLE_STARTED); ClrBit(w->vehicle_flags, VF_TIMETABLE_STARTED);

@ -837,8 +837,7 @@ static void RestoreTrainBackup(TrainList &list)
Train *prev = NULL; Train *prev = NULL;
/* Iterate over the list and rebuild it. */ /* Iterate over the list and rebuild it. */
for (Train **iter = list.Begin(); iter != list.End(); iter++) { for (Train *t : list) {
Train *t = *iter;
if (prev != NULL) { if (prev != NULL) {
prev->SetNext(t); prev->SetNext(t);
} else if (t->Previous() != NULL) { } else if (t->Previous() != NULL) {

@ -278,10 +278,10 @@ static void GetCargoSummaryOfArticulatedVehicle(const Train *v, CargoSummary *su
new_item.subtype = GetCargoSubtypeText(v); new_item.subtype = GetCargoSubtypeText(v);
if (new_item.cargo == INVALID_CARGO && new_item.subtype == STR_EMPTY) continue; if (new_item.cargo == INVALID_CARGO && new_item.subtype == STR_EMPTY) continue;
CargoSummaryItem *item = &*std::find(summary->begin(), summary->end(), new_item); auto item = std::find(summary->begin(), summary->end(), new_item);
if (item == summary->End()) { if (item == summary->end()) {
/*C++17: item = &*/ summary->emplace_back(); summary->emplace_back();
item = &summary->back(); item = summary->end() - 1;
item->cargo = new_item.cargo; item->cargo = new_item.cargo;
item->subtype = new_item.subtype; item->subtype = new_item.subtype;
item->capacity = 0; item->capacity = 0;

@ -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 * Deliberately clear the coa pointer to avoid leaving dangling pointers which could
* inadvertently be dereferenced. * inadvertently be dereferenced.
*/ */
assert(coa >= _cleared_object_areas.Begin() && coa < _cleared_object_areas.End()); ClearedObjectArea *begin = _cleared_object_areas.data();
size_t coa_index = coa - _cleared_object_areas.Begin(); 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 assert(coa_index < UINT_MAX); // more than 2**32 cleared areas would be a bug in itself
coa = NULL; coa = NULL;

@ -1028,15 +1028,15 @@ void CallVehicleTicks()
} }
Backup<CompanyByte> cur_company(_current_company, FILE_LINE); Backup<CompanyByte> cur_company(_current_company, FILE_LINE);
for (AutoreplaceMap::iterator it = _vehicles_to_autoreplace.Begin(); it != _vehicles_to_autoreplace.End(); it++) { for (auto &it : _vehicles_to_autoreplace) {
v = it->first; v = it.first;
/* Autoreplace needs the current company set as the vehicle owner */ /* Autoreplace needs the current company set as the vehicle owner */
cur_company.Change(v->owner); cur_company.Change(v->owner);
/* Start vehicle if we stopped them in VehicleEnteredDepotThisTick() /* Start vehicle if we stopped them in VehicleEnteredDepotThisTick()
* We need to stop them between VehicleEnteredDepotThisTick() and here or we risk that * We need to stop them between VehicleEnteredDepotThisTick() and here or we risk that
* they are already leaving the depot again before being replaced. */ * 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 */ /* Store the position of the effect as the vehicle pointer will become invalid later */
int x = v->x_pos; int x = v->x_pos;

@ -422,17 +422,17 @@ static CommandCost RefitVehicle(Vehicle *v, bool only_this, uint8 num_vehicles,
if (flags & DC_EXEC) { if (flags & DC_EXEC) {
/* Store the result */ /* Store the result */
for (RefitResult *result = refit_result.Begin(); result != refit_result.End(); result++) { for (RefitResult &result : refit_result) {
Vehicle *u = result->v; Vehicle *u = result.v;
u->refit_cap = (u->cargo_type == new_cid) ? min(result->capacity, u->refit_cap) : 0; 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); if (u->cargo.TotalCount() > u->refit_cap) u->cargo.Truncate(u->cargo.TotalCount() - u->refit_cap);
u->cargo_type = new_cid; u->cargo_type = new_cid;
u->cargo_cap = result->capacity; u->cargo_cap = result.capacity;
u->cargo_subtype = result->subtype; u->cargo_subtype = result.subtype;
if (u->type == VEH_AIRCRAFT) { if (u->type == VEH_AIRCRAFT) {
Vehicle *w = u->Next(); Vehicle *w = u->Next();
w->refit_cap = min(w->refit_cap, result->mail_capacity); w->refit_cap = min(w->refit_cap, result.mail_capacity);
w->cargo_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); if (w->cargo.TotalCount() > w->refit_cap) w->cargo.Truncate(w->cargo.TotalCount() - w->refit_cap);
} }
} }

@ -106,8 +106,8 @@ const StringID BaseVehicleListWindow::vehicle_depot_name[] = {
uint GetUnitNumberDigits(VehicleList &vehicles) uint GetUnitNumberDigits(VehicleList &vehicles)
{ {
uint unitnumber = 0; uint unitnumber = 0;
for (const Vehicle **v = vehicles.Begin(); v != vehicles.End(); v++) { for (const Vehicle *v : vehicles) {
unitnumber = max<uint>(unitnumber, (*v)->unitnumber); unitnumber = max<uint>(unitnumber, v->unitnumber);
} }
if (unitnumber >= 10000) return 5; if (unitnumber >= 10000) return 5;
@ -194,7 +194,7 @@ void BaseVehicleListWindow::SortVehicleList()
void DepotSortList(VehicleList *list) void DepotSortList(VehicleList *list)
{ {
if (list->size() < 2) return; 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. */ /** draw the vehicle profit button in the vehicle list window. */

@ -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) pt.y + spr->y_offs + spr->height <= _vd.dpi.top)
return; return;
const ParentSpriteToDraw *pstd = _vd.parent_sprites_to_draw.End() - 1; const ParentSpriteToDraw &pstd = _vd.parent_sprites_to_draw.back();
AddChildSpriteScreen(image, pal, pt.x - pstd->left, pt.y - pstd->top, false, sub, false); 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) static void ViewportDrawTileSprites(const TileSpriteToDrawVector *tstdv)
{ {
const TileSpriteToDraw *tsend = tstdv->End(); for (const TileSpriteToDraw &ts : *tstdv) {
for (const TileSpriteToDraw *ts = tstdv->Begin(); ts != tsend; ++ts) { DrawSpriteViewport(ts.image, ts.pal, ts.x, ts.y, ts.sub);
DrawSpriteViewport(ts->image, ts->pal, ts->x, ts->y, ts->sub);
} }
} }
@ -1408,8 +1407,8 @@ static bool ViewportSortParentSpritesChecker()
/** Sort parent sprites pointer array */ /** Sort parent sprites pointer array */
static void ViewportSortParentSprites(ParentSpriteToSortVector *psdv) static void ViewportSortParentSprites(ParentSpriteToSortVector *psdv)
{ {
ParentSpriteToDraw **psdvend = psdv->End(); auto psdvend = psdv->end();
ParentSpriteToDraw **psd = psdv->Begin(); auto psd = psdv->begin();
while (psd != psdvend) { while (psd != psdvend) {
ParentSpriteToDraw *ps = *psd; ParentSpriteToDraw *ps = *psd;
@ -1420,7 +1419,7 @@ static void ViewportSortParentSprites(ParentSpriteToSortVector *psdv)
ps->comparison_done = true; ps->comparison_done = true;
for (ParentSpriteToDraw **psd2 = psd + 1; psd2 != psdvend; psd2++) { for (auto psd2 = psd + 1; psd2 != psdvend; psd2++) {
ParentSpriteToDraw *ps2 = *psd2; ParentSpriteToDraw *ps2 = *psd2;
if (ps2->comparison_done) continue; if (ps2->comparison_done) continue;
@ -1455,7 +1454,7 @@ static void ViewportSortParentSprites(ParentSpriteToSortVector *psdv)
/* Move ps2 in front of ps */ /* Move ps2 in front of ps */
ParentSpriteToDraw *temp = ps2; ParentSpriteToDraw *temp = ps2;
for (ParentSpriteToDraw **psd3 = psd2; psd3 > psd; psd3--) { for (auto psd3 = psd2; psd3 > psd; psd3--) {
*psd3 = *(psd3 - 1); *psd3 = *(psd3 - 1);
} }
*psd = temp; *psd = temp;
@ -1465,9 +1464,7 @@ static void ViewportSortParentSprites(ParentSpriteToSortVector *psdv)
static void ViewportDrawParentSprites(const ParentSpriteToSortVector *psd, const ChildScreenSpriteToDrawVector *csstdv) static void ViewportDrawParentSprites(const ParentSpriteToSortVector *psd, const ChildScreenSpriteToDrawVector *csstdv)
{ {
const ParentSpriteToDraw * const *psd_end = psd->End(); for (const ParentSpriteToDraw *ps : *psd) {
for (const ParentSpriteToDraw * const *it = psd->Begin(); it != psd_end; it++) {
const ParentSpriteToDraw *ps = *it;
if (ps->image != SPR_EMPTY_BOUNDING_BOX) DrawSpriteViewport(ps->image, ps->pal, ps->x, ps->y, ps->sub); if (ps->image != SPR_EMPTY_BOUNDING_BOX) DrawSpriteViewport(ps->image, ps->pal, ps->x, ps->y, ps->sub);
int child_idx = ps->first_child; int child_idx = ps->first_child;
@ -1485,9 +1482,7 @@ static void ViewportDrawParentSprites(const ParentSpriteToSortVector *psd, const
*/ */
static void ViewportDrawBoundingBoxes(const ParentSpriteToSortVector *psd) static void ViewportDrawBoundingBoxes(const ParentSpriteToSortVector *psd)
{ {
const ParentSpriteToDraw * const *psd_end = psd->End(); for (const ParentSpriteToDraw *ps : *psd) {
for (const ParentSpriteToDraw * const *it = psd->Begin(); it != psd_end; it++) {
const ParentSpriteToDraw *ps = *it;
Point pt1 = RemapCoords(ps->xmax + 1, ps->ymax + 1, ps->zmax + 1); // top front corner 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 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 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) static void ViewportDrawStrings(ZoomLevel zoom, const StringSpriteToDrawVector *sstdv)
{ {
const StringSpriteToDraw *ssend = sstdv->End(); for (const StringSpriteToDraw &ss : *sstdv) {
for (const StringSpriteToDraw *ss = sstdv->Begin(); ss != ssend; ++ss) {
TextColour colour = TC_BLACK; TextColour colour = TC_BLACK;
bool small = HasBit(ss->width, 15); bool small = HasBit(ss.width, 15);
int w = GB(ss->width, 0, 15); int w = GB(ss.width, 0, 15);
int x = UnScaleByZoom(ss->x, zoom); int x = UnScaleByZoom(ss.x, zoom);
int y = UnScaleByZoom(ss->y, zoom); int y = UnScaleByZoom(ss.y, zoom);
int h = VPSM_TOP + (small ? FONT_HEIGHT_SMALL : FONT_HEIGHT_NORMAL) + VPSM_BOTTOM; int h = VPSM_TOP + (small ? FONT_HEIGHT_SMALL : FONT_HEIGHT_NORMAL) + VPSM_BOTTOM;
SetDParam(0, ss->params[0]); SetDParam(0, ss.params[0]);
SetDParam(1, ss->params[1]); 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 */ /* 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. /* Don't draw the rectangle.
* Real colours need the TC_IS_PALETTE_COLOUR flag. * Real colours need the TC_IS_PALETTE_COLOUR flag.
* Otherwise colours from _string_colourmap are assumed. */ * 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 { } else {
/* Draw the rectangle if 'transparent station signs' is off, /* Draw the rectangle if 'transparent station signs' is off,
* or if we are drawing a general text sign (STR_WHITE_SIGN). */ * or if we are drawing a general text sign (STR_WHITE_SIGN). */
DrawFrameRect( DrawFrameRect(
x, y, x + w, y + h, ss->colour, x, y, x + w, y + h, ss.colour,
IsTransparencySet(TO_SIGNS) ? FR_TRANSPARENT : FR_NONE 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); if (_vd.tile_sprites_to_draw.size() != 0) ViewportDrawTileSprites(&_vd.tile_sprites_to_draw);
ParentSpriteToDraw *psd_end = _vd.parent_sprites_to_draw.End(); for (auto &psd : _vd.parent_sprites_to_draw) {
for (ParentSpriteToDraw *it = _vd.parent_sprites_to_draw.Begin(); it != psd_end; it++) { _vd.parent_sprites_to_sort.push_back(&psd);
_vd.parent_sprites_to_sort.push_back(it);
} }
_vp_sprite_sorter(&_vd.parent_sprites_to_sort); _vp_sprite_sorter(&_vd.parent_sprites_to_sort);

@ -29,8 +29,8 @@
void ViewportSortParentSpritesSSE41(ParentSpriteToSortVector *psdv) 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); 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(); auto const psdvend = psdv->end();
ParentSpriteToDraw **psd = psdv->Begin(); auto psd = psdv->begin();
while (psd != psdvend) { while (psd != psdvend) {
ParentSpriteToDraw * const ps = *psd; ParentSpriteToDraw * const ps = *psd;
@ -41,7 +41,7 @@ void ViewportSortParentSpritesSSE41(ParentSpriteToSortVector *psdv)
ps->comparison_done = true; ps->comparison_done = true;
for (ParentSpriteToDraw **psd2 = psd + 1; psd2 != psdvend; psd2++) { for (auto psd2 = psd + 1; psd2 != psdvend; psd2++) {
ParentSpriteToDraw * const ps2 = *psd2; ParentSpriteToDraw * const ps2 = *psd2;
if (ps2->comparison_done) continue; if (ps2->comparison_done) continue;
@ -85,7 +85,7 @@ void ViewportSortParentSpritesSSE41(ParentSpriteToSortVector *psdv)
/* Move ps2 in front of ps */ /* Move ps2 in front of ps */
ParentSpriteToDraw * const temp = ps2; ParentSpriteToDraw * const temp = ps2;
for (ParentSpriteToDraw **psd3 = psd2; psd3 > psd; psd3--) { for (auto psd3 = psd2; psd3 > psd; psd3--) {
*psd3 = *(psd3 - 1); *psd3 = *(psd3 - 1);
} }
*psd = temp; *psd = temp;

@ -174,8 +174,7 @@ struct DropdownWindow : Window {
/* Total length of list */ /* Total length of list */
int list_height = 0; int list_height = 0;
for (const DropDownListItem * const *it = list->Begin(); it != list->End(); ++it) { for (const DropDownListItem *item : *list) {
const DropDownListItem *item = *it;
list_height += item->Height(items_width); list_height += item->Height(items_width);
} }
@ -230,13 +229,10 @@ struct DropdownWindow : Window {
int width = nwi->current_x - 4; int width = nwi->current_x - 4;
int pos = this->vscroll->GetPosition(); int pos = this->vscroll->GetPosition();
const DropDownList *list = this->list; for (const DropDownListItem *item : *this->list) {
for (const DropDownListItem * const *it = list->Begin(); it != list->End(); ++it) {
/* Skip items that are scrolled up */ /* Skip items that are scrolled up */
if (--pos >= 0) continue; if (--pos >= 0) continue;
const DropDownListItem *item = *it;
int item_height = item->Height(width); int item_height = item->Height(width);
if (y < item_height) { if (y < item_height) {
@ -259,8 +255,7 @@ struct DropdownWindow : Window {
int y = r.top + 2; int y = r.top + 2;
int pos = this->vscroll->GetPosition(); int pos = this->vscroll->GetPosition();
for (const DropDownListItem * const *it = this->list->Begin(); it != this->list->End(); ++it) { for (const DropDownListItem *item : *this->list) {
const DropDownListItem *item = *it;
int item_height = item->Height(r.right - r.left + 1); int item_height = item->Height(r.right - r.left + 1);
/* Skip items that are scrolled up */ /* 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 */ /* Total height of list */
uint height = 0; uint height = 0;
for (const DropDownListItem * const *it = list->Begin(); it != list->End(); ++it) { for (const DropDownListItem *item : *list) {
const DropDownListItem *item = *it;
height += item->Height(width); height += item->Height(width);
if (auto_width) max_item_width = max(max_item_width, item->Width() + 5); if (auto_width) max_item_width = max(max_item_width, item->Width() + 5);
} }

@ -144,9 +144,9 @@ void WindowDesc::LoadFromConfig()
{ {
IniFile *ini = new IniFile(); IniFile *ini = new IniFile();
ini->LoadFromDisk(_windows_file, NO_DIRECTORY); ini->LoadFromDisk(_windows_file, NO_DIRECTORY);
for (WindowDesc **it = _window_descs->Begin(); it != _window_descs->End(); ++it) { for (WindowDesc *wd : *_window_descs) {
if ((*it)->ini_key == NULL) continue; if (wd->ini_key == NULL) continue;
IniLoadWindowSettings(ini, (*it)->ini_key, *it); IniLoadWindowSettings(ini, wd->ini_key, wd);
} }
delete ini; delete ini;
} }
@ -166,13 +166,13 @@ static int CDECL DescSorter(WindowDesc * const *a, WindowDesc * const *b)
void WindowDesc::SaveToConfig() void WindowDesc::SaveToConfig()
{ {
/* Sort the stuff to get a nice ini file on first write */ /* 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(); IniFile *ini = new IniFile();
ini->LoadFromDisk(_windows_file, NO_DIRECTORY); ini->LoadFromDisk(_windows_file, NO_DIRECTORY);
for (WindowDesc **it = _window_descs->Begin(); it != _window_descs->End(); ++it) { for (WindowDesc *wd : *_window_descs) {
if ((*it)->ini_key == NULL) continue; if (wd->ini_key == NULL) continue;
IniSaveWindowSettings(ini, (*it)->ini_key, *it); IniSaveWindowSettings(ini, wd->ini_key, wd);
} }
ini->SaveToDisk(_windows_file); ini->SaveToDisk(_windows_file);
delete ini; delete ini;
@ -330,8 +330,8 @@ Scrollbar *Window::GetScrollbar(uint widnum)
*/ */
const QueryString *Window::GetQueryString(uint widnum) const const QueryString *Window::GetQueryString(uint widnum) const
{ {
const SmallMap<int, QueryString*>::Pair *query = this->querystrings.Find(widnum); auto query = this->querystrings.Find(widnum);
return query != this->querystrings.End() ? query->second : NULL; return query != this->querystrings.end() ? query->second : NULL;
} }
/** /**
@ -1944,8 +1944,8 @@ static void DecreaseWindowCounters()
} }
/* Handle editboxes */ /* Handle editboxes */
for (SmallMap<int, QueryString*>::Pair *it = w->querystrings.Begin(); it != w->querystrings.End(); ++it) { for (SmallMap<int, QueryString*>::Pair &pair : w->querystrings) {
it->second->HandleEditBox(w, it->first); pair.second->HandleEditBox(w, pair.first);
} }
w->OnMouseLoop(); w->OnMouseLoop();
@ -3252,8 +3252,9 @@ void Window::InvalidateData(int data, bool gui_scope)
*/ */
void Window::ProcessScheduledInvalidations() void Window::ProcessScheduledInvalidations()
{ {
for (int *data = this->scheduled_invalidation_data.Begin(); this->window_class != WC_INVALID && data != this->scheduled_invalidation_data.End(); data++) { for (int data : this->scheduled_invalidation_data) {
this->OnInvalidateData(*data, true); if (this->window_class == WC_INVALID) break;
this->OnInvalidateData(data, true);
} }
this->scheduled_invalidation_data.clear(); this->scheduled_invalidation_data.clear();
} }

Loading…
Cancel
Save