Use 'auto', range-'for', and structured bindings to improve some loops

This commit is contained in:
Vittorio Romeo 2021-12-08 01:08:11 +00:00 committed by Lukas Dürrenberger
parent ce5d410c74
commit 8be8a76cba
23 changed files with 171 additions and 168 deletions

View File

@ -102,9 +102,8 @@ int main()
// Print the contents of the current server directory // Print the contents of the current server directory
sf::Ftp::ListingResponse response = server.getDirectoryListing(); sf::Ftp::ListingResponse response = server.getDirectoryListing();
std::cout << response << std::endl; std::cout << response << std::endl;
const std::vector<std::string>& names = response.getListing(); for (const std::string& name : response.getListing())
for (std::vector<std::string>::const_iterator it = names.begin(); it != names.end(); ++it) std::cout << name << std::endl;
std::cout << *it << std::endl;
break; break;
} }

View File

@ -142,15 +142,15 @@ int main()
object.value.setString("N/A"); object.value.setString("N/A");
} }
for (Texts::iterator it = texts.begin(); it != texts.end(); ++it) for (auto& [label, joystickObject] : texts)
{ {
it->second.label.setFont(font); joystickObject.label.setFont(font);
it->second.label.setCharacterSize(14); joystickObject.label.setCharacterSize(14);
it->second.label.setFillColor(sf::Color::White); joystickObject.label.setFillColor(sf::Color::White);
it->second.value.setFont(font); joystickObject.value.setFont(font);
it->second.value.setCharacterSize(14); joystickObject.value.setCharacterSize(14);
it->second.value.setFillColor(sf::Color::White); joystickObject.value.setFillColor(sf::Color::White);
} }
// Update initially displayed joystick values if a joystick is already connected on startup // Update initially displayed joystick values if a joystick is already connected on startup
@ -187,8 +187,8 @@ int main()
else if (event.type == sf::Event::JoystickDisconnected) else if (event.type == sf::Event::JoystickDisconnected)
{ {
// Reset displayed joystick values to empty // Reset displayed joystick values to empty
for (Texts::iterator it = texts.begin(); it != texts.end(); ++it) for (auto& [label, joystickObject] : texts)
it->second.value.setString("N/A"); joystickObject.value.setString("N/A");
texts["ID"].label.setString("<Not Connected>"); texts["ID"].label.setString("<Not Connected>");
texts["ID"].value.setString(""); texts["ID"].value.setString("");
@ -226,10 +226,10 @@ int main()
window.clear(); window.clear();
// Draw the label-value sf::Text objects // Draw the label-value sf::Text objects
for (Texts::const_iterator it = texts.begin(); it != texts.end(); ++it) for (const auto& [label, joystickObject] : texts)
{ {
window.draw(it->second.label); window.draw(joystickObject.label);
window.draw(it->second.value); window.draw(joystickObject.value);
} }
// Display things on screen // Display things on screen

View File

@ -57,7 +57,7 @@ template <typename T>
void SoundFileFactory::unregisterReader() void SoundFileFactory::unregisterReader()
{ {
// Remove the instance(s) of the reader from the array of factories // Remove the instance(s) of the reader from the array of factories
for (ReaderFactoryArray::iterator it = s_readers.begin(); it != s_readers.end(); ) for (auto it = s_readers.begin(); it != s_readers.end(); /* noop */)
{ {
if (it->create == &priv::createReader<T>) if (it->create == &priv::createReader<T>)
it = s_readers.erase(it); it = s_readers.erase(it);
@ -88,7 +88,7 @@ template <typename T>
void SoundFileFactory::unregisterWriter() void SoundFileFactory::unregisterWriter()
{ {
// Remove the instance(s) of the writer from the array of factories // Remove the instance(s) of the writer from the array of factories
for (WriterFactoryArray::iterator it = s_writers.begin(); it != s_writers.end(); ) for (auto it = s_writers.begin(); it != s_writers.end(); /* noop */)
{ {
if (it->create == &priv::createWriter<T>) if (it->create == &priv::createWriter<T>)
it = s_writers.erase(it); it = s_writers.erase(it);

View File

@ -240,7 +240,7 @@ private:
/// else /// else
/// { /// {
/// // The listener socket is not ready, test all other sockets (the clients) /// // The listener socket is not ready, test all other sockets (the clients)
/// for (std::list<sf::TcpSocket*>::iterator it = clients.begin(); it != clients.end(); ++it) /// for (auto it = clients.begin(); it != clients.end(); ++it)
/// { /// {
/// sf::TcpSocket& client = **it; /// sf::TcpSocket& client = **it;
/// if (selector.isReady(client)) /// if (selector.isReady(client))

View File

@ -72,8 +72,8 @@ SoundBuffer::~SoundBuffer()
sounds.swap(m_sounds); sounds.swap(m_sounds);
// Detach the buffer from the sounds that use it (to avoid OpenAL errors) // Detach the buffer from the sounds that use it (to avoid OpenAL errors)
for (SoundList::const_iterator it = sounds.begin(); it != sounds.end(); ++it) for (Sound* soundPtr : sounds)
(*it)->resetBuffer(); soundPtr->resetBuffer();
// Destroy the buffer // Destroy the buffer
if (m_buffer) if (m_buffer)
@ -257,8 +257,8 @@ bool SoundBuffer::update(unsigned int channelCount, unsigned int sampleRate)
SoundList sounds(m_sounds); SoundList sounds(m_sounds);
// Detach the buffer from the sounds that use it (to avoid OpenAL errors) // Detach the buffer from the sounds that use it (to avoid OpenAL errors)
for (SoundList::const_iterator it = sounds.begin(); it != sounds.end(); ++it) for (Sound* soundPtr : sounds)
(*it)->resetBuffer(); soundPtr->resetBuffer();
// Fill the buffer // Fill the buffer
ALsizei size = static_cast<ALsizei>(m_samples.size() * sizeof(Int16)); ALsizei size = static_cast<ALsizei>(m_samples.size() * sizeof(Int16));
@ -268,8 +268,8 @@ bool SoundBuffer::update(unsigned int channelCount, unsigned int sampleRate)
m_duration = seconds(static_cast<float>(m_samples.size()) / static_cast<float>(sampleRate) / static_cast<float>(channelCount)); m_duration = seconds(static_cast<float>(m_samples.size()) / static_cast<float>(sampleRate) / static_cast<float>(channelCount));
// Now reattach the buffer to the sounds that use it // Now reattach the buffer to the sounds that use it
for (SoundList::const_iterator it = sounds.begin(); it != sounds.end(); ++it) for (Sound* soundPtr : sounds)
(*it)->setBuffer(*this); soundPtr->setBuffer(*this);
return true; return true;
} }

View File

@ -76,11 +76,11 @@ SoundFileReader* SoundFileFactory::createReaderFromFilename(const std::string& f
} }
// Test the filename in all the registered factories // Test the filename in all the registered factories
for (ReaderFactoryArray::const_iterator it = s_readers.begin(); it != s_readers.end(); ++it) for (const ReaderFactory& readerFactory : s_readers)
{ {
stream.seek(0); stream.seek(0);
if (it->check(stream)) if (readerFactory.check(stream))
return it->create(); return readerFactory.create();
} }
// No suitable reader found // No suitable reader found
@ -100,11 +100,11 @@ SoundFileReader* SoundFileFactory::createReaderFromMemory(const void* data, std:
stream.open(data, sizeInBytes); stream.open(data, sizeInBytes);
// Test the stream for all the registered factories // Test the stream for all the registered factories
for (ReaderFactoryArray::const_iterator it = s_readers.begin(); it != s_readers.end(); ++it) for (const ReaderFactory& readerFactory : s_readers)
{ {
stream.seek(0); stream.seek(0);
if (it->check(stream)) if (readerFactory.check(stream))
return it->create(); return readerFactory.create();
} }
// No suitable reader found // No suitable reader found
@ -120,11 +120,11 @@ SoundFileReader* SoundFileFactory::createReaderFromStream(InputStream& stream)
ensureDefaultReadersWritersRegistered(); ensureDefaultReadersWritersRegistered();
// Test the stream for all the registered factories // Test the stream for all the registered factories
for (ReaderFactoryArray::const_iterator it = s_readers.begin(); it != s_readers.end(); ++it) for (const ReaderFactory& readerFactory : s_readers)
{ {
stream.seek(0); stream.seek(0);
if (it->check(stream)) if (readerFactory.check(stream))
return it->create(); return readerFactory.create();
} }
// No suitable reader found // No suitable reader found
@ -140,10 +140,10 @@ SoundFileWriter* SoundFileFactory::createWriterFromFilename(const std::string& f
ensureDefaultReadersWritersRegistered(); ensureDefaultReadersWritersRegistered();
// Test the filename in all the registered factories // Test the filename in all the registered factories
for (WriterFactoryArray::const_iterator it = s_writers.begin(); it != s_writers.end(); ++it) for (const WriterFactory& writerFactory : s_writers)
{ {
if (it->check(filename)) if (writerFactory.check(filename))
return it->create(); return writerFactory.create();
} }
// No suitable writer found // No suitable writer found

View File

@ -354,8 +354,7 @@ const Glyph& Font::getGlyph(Uint32 codePoint, unsigned int characterSize, bool b
Uint64 key = combine(outlineThickness, bold, FT_Get_Char_Index(static_cast<FT_Face>(m_face), codePoint)); Uint64 key = combine(outlineThickness, bold, FT_Get_Char_Index(static_cast<FT_Face>(m_face), codePoint));
// Search the glyph into the cache // Search the glyph into the cache
GlyphTable::const_iterator it = glyphs.find(key); if (auto it = glyphs.find(key); it != glyphs.end())
if (it != glyphs.end())
{ {
// Found: just return it // Found: just return it
return it->second; return it->second;
@ -486,9 +485,9 @@ void Font::setSmooth(bool smooth)
{ {
m_isSmooth = smooth; m_isSmooth = smooth;
for (sf::Font::PageTable::iterator page = m_pages.begin(); page != m_pages.end(); ++page) for (auto& [key, page] : m_pages)
{ {
page->second.texture.setSmooth(m_isSmooth); page.texture.setSmooth(m_isSmooth);
} }
} }
} }
@ -737,7 +736,7 @@ IntRect Font::findGlyphRect(Page& page, unsigned int width, unsigned int height)
// Find the line that fits well the glyph // Find the line that fits well the glyph
Row* row = nullptr; Row* row = nullptr;
float bestRatio = 0; float bestRatio = 0;
for (std::vector<Row>::iterator it = page.rows.begin(); it != page.rows.end() && !row; ++it) for (auto it = page.rows.begin(); it != page.rows.end() && !row; ++it)
{ {
float ratio = static_cast<float>(height) / static_cast<float>(it->height); float ratio = static_cast<float>(height) / static_cast<float>(it->height);

View File

@ -308,8 +308,8 @@ void Image::flipHorizontally()
for (std::size_t y = 0; y < m_size.y; ++y) for (std::size_t y = 0; y < m_size.y; ++y)
{ {
std::vector<Uint8>::iterator left = m_pixels.begin() + static_cast<std::vector<Uint8>::iterator::difference_type>(y * rowSize); auto left = m_pixels.begin() + static_cast<std::vector<Uint8>::iterator::difference_type>(y * rowSize);
std::vector<Uint8>::iterator right = m_pixels.begin() + static_cast<std::vector<Uint8>::iterator::difference_type>((y + 1) * rowSize - 4); auto right = m_pixels.begin() + static_cast<std::vector<Uint8>::iterator::difference_type>((y + 1) * rowSize - 4);
for (std::size_t x = 0; x < m_size.x / 2; ++x) for (std::size_t x = 0; x < m_size.x / 2; ++x)
{ {
@ -328,10 +328,10 @@ void Image::flipVertically()
{ {
if (!m_pixels.empty()) if (!m_pixels.empty())
{ {
std::vector<Uint8>::iterator::difference_type rowSize = static_cast<std::vector<Uint8>::iterator::difference_type>(m_size.x * 4); auto rowSize = static_cast<std::vector<Uint8>::iterator::difference_type>(m_size.x * 4);
std::vector<Uint8>::iterator top = m_pixels.begin(); auto top = m_pixels.begin();
std::vector<Uint8>::iterator bottom = m_pixels.end() - rowSize; auto bottom = m_pixels.end() - rowSize;
for (std::size_t y = 0; y < m_size.y / 2; ++y) for (std::size_t y = 0; y < m_size.y / 2; ++y)
{ {

View File

@ -41,8 +41,9 @@ namespace
// Convert a string to lower case // Convert a string to lower case
std::string toLower(std::string str) std::string toLower(std::string str)
{ {
for (std::string::iterator i = str.begin(); i != str.end(); ++i) for (char& c : str)
*i = static_cast<char>(std::tolower(*i)); c = static_cast<char>(std::tolower(c));
return str; return str;
} }

View File

@ -77,9 +77,9 @@ namespace
// Check if a RenderTarget with the given ID is active in the current context // Check if a RenderTarget with the given ID is active in the current context
bool isActive(sf::Uint64 id) bool isActive(sf::Uint64 id)
{ {
ContextRenderTargetMap::iterator iter = contextRenderTargetMap.find(sf::Context::getActiveContextId()); auto it = contextRenderTargetMap.find(sf::Context::getActiveContextId());
if ((iter == contextRenderTargetMap.end()) || (iter->second != id)) if ((it == contextRenderTargetMap.end()) || (it->second != id))
return false; return false;
return true; return true;
@ -433,28 +433,28 @@ bool RenderTarget::setActive(bool active)
Uint64 contextId = Context::getActiveContextId(); Uint64 contextId = Context::getActiveContextId();
using RenderTargetImpl::contextRenderTargetMap; using RenderTargetImpl::contextRenderTargetMap;
RenderTargetImpl::ContextRenderTargetMap::iterator iter = contextRenderTargetMap.find(contextId); auto it = contextRenderTargetMap.find(contextId);
if (active) if (active)
{ {
if (iter == contextRenderTargetMap.end()) if (it == contextRenderTargetMap.end())
{ {
contextRenderTargetMap[contextId] = m_id; contextRenderTargetMap[contextId] = m_id;
m_cache.glStatesSet = false; m_cache.glStatesSet = false;
m_cache.enable = false; m_cache.enable = false;
} }
else if (iter->second != m_id) else if (it->second != m_id)
{ {
iter->second = m_id; it->second = m_id;
m_cache.enable = false; m_cache.enable = false;
} }
} }
else else
{ {
if (iter != contextRenderTargetMap.end()) if (it != contextRenderTargetMap.end())
contextRenderTargetMap.erase(iter); contextRenderTargetMap.erase(it);
m_cache.enable = false; m_cache.enable = false;
} }

View File

@ -62,18 +62,18 @@ namespace
{ {
sf::Uint64 contextId = sf::Context::getActiveContextId(); sf::Uint64 contextId = sf::Context::getActiveContextId();
for (std::set<std::pair<sf::Uint64, unsigned int> >::iterator iter = staleFrameBuffers.begin(); iter != staleFrameBuffers.end();) for (auto it = staleFrameBuffers.begin(); it != staleFrameBuffers.end();)
{ {
if (iter->first == contextId) if (it->first == contextId)
{ {
GLuint frameBuffer = static_cast<GLuint>(iter->second); GLuint frameBuffer = static_cast<GLuint>(it->second);
glCheck(GLEXT_glDeleteFramebuffers(1, &frameBuffer)); glCheck(GLEXT_glDeleteFramebuffers(1, &frameBuffer));
staleFrameBuffers.erase(iter++); staleFrameBuffers.erase(it++);
} }
else else
{ {
++iter; ++it;
} }
} }
} }
@ -86,17 +86,17 @@ namespace
sf::Uint64 contextId = sf::Context::getActiveContextId(); sf::Uint64 contextId = sf::Context::getActiveContextId();
// Destroy active frame buffer objects // Destroy active frame buffer objects
for (std::unordered_set<std::unordered_map<sf::Uint64, unsigned int>*>::iterator frameBuffersIter = frameBuffers.begin(); frameBuffersIter != frameBuffers.end(); ++frameBuffersIter) for (auto* frameBuffer : frameBuffers)
{ {
for (std::unordered_map<sf::Uint64, unsigned int>::iterator iter = (*frameBuffersIter)->begin(); iter != (*frameBuffersIter)->end(); ++iter) for (auto it = frameBuffer->begin(); it != frameBuffer->end(); ++it)
{ {
if (iter->first == contextId) if (it->first == contextId)
{ {
GLuint frameBuffer = iter->second; GLuint frameBufferId = it->second;
glCheck(GLEXT_glDeleteFramebuffers(1, &frameBuffer)); glCheck(GLEXT_glDeleteFramebuffers(1, &frameBufferId));
// Erase the entry from the RenderTextureImplFBO's map // Erase the entry from the RenderTextureImplFBO's map
(*frameBuffersIter)->erase(iter); frameBuffer->erase(it);
break; break;
} }
@ -162,11 +162,11 @@ RenderTextureImplFBO::~RenderTextureImplFBO()
} }
// Move all frame buffer objects to stale set // Move all frame buffer objects to stale set
for (std::unordered_map<Uint64, unsigned int>::iterator iter = m_frameBuffers.begin(); iter != m_frameBuffers.end(); ++iter) for (auto& [contextId, frameBufferId] : m_frameBuffers)
staleFrameBuffers.emplace(iter->first, iter->second); staleFrameBuffers.emplace(contextId, frameBufferId);
for (std::unordered_map<Uint64, unsigned int>::iterator iter = m_multisampleFrameBuffers.begin(); iter != m_multisampleFrameBuffers.end(); ++iter) for (auto& [contextId, multisampleFrameBufferId] : m_multisampleFrameBuffers)
staleFrameBuffers.emplace(iter->first, iter->second); staleFrameBuffers.emplace(contextId, multisampleFrameBufferId);
// Clean up FBOs // Clean up FBOs
destroyStaleFBOs(); destroyStaleFBOs();
@ -542,26 +542,26 @@ bool RenderTextureImplFBO::activate(bool active)
{ {
Lock lock(mutex); Lock lock(mutex);
std::unordered_map<Uint64, unsigned int>::iterator iter; std::unordered_map<Uint64, unsigned int>::iterator it;
if (m_multisample) if (m_multisample)
{ {
iter = m_multisampleFrameBuffers.find(contextId); it = m_multisampleFrameBuffers.find(contextId);
if (iter != m_multisampleFrameBuffers.end()) if (it != m_multisampleFrameBuffers.end())
{ {
glCheck(GLEXT_glBindFramebuffer(GLEXT_GL_FRAMEBUFFER, iter->second)); glCheck(GLEXT_glBindFramebuffer(GLEXT_GL_FRAMEBUFFER, it->second));
return true; return true;
} }
} }
else else
{ {
iter = m_frameBuffers.find(contextId); it = m_frameBuffers.find(contextId);
if (iter != m_frameBuffers.end()) if (it != m_frameBuffers.end())
{ {
glCheck(GLEXT_glBindFramebuffer(GLEXT_GL_FRAMEBUFFER, iter->second)); glCheck(GLEXT_glBindFramebuffer(GLEXT_GL_FRAMEBUFFER, it->second));
return true; return true;
} }
@ -596,15 +596,15 @@ void RenderTextureImplFBO::updateTexture(unsigned int)
Lock lock(mutex); Lock lock(mutex);
std::unordered_map<Uint64, unsigned int>::iterator iter = m_frameBuffers.find(contextId); auto frameBufferIt = m_frameBuffers.find(contextId);
std::unordered_map<Uint64, unsigned int>::iterator multisampleIter = m_multisampleFrameBuffers.find(contextId); auto multisampleIt = m_multisampleFrameBuffers.find(contextId);
if ((iter != m_frameBuffers.end()) && (multisampleIter != m_multisampleFrameBuffers.end())) if ((frameBufferIt != m_frameBuffers.end()) && (multisampleIt != m_multisampleFrameBuffers.end()))
{ {
// Set up the blit target (draw framebuffer) and blit (from the read framebuffer, our multisample FBO) // Set up the blit target (draw framebuffer) and blit (from the read framebuffer, our multisample FBO)
glCheck(GLEXT_glBindFramebuffer(GLEXT_GL_DRAW_FRAMEBUFFER, iter->second)); glCheck(GLEXT_glBindFramebuffer(GLEXT_GL_DRAW_FRAMEBUFFER, frameBufferIt->second));
glCheck(GLEXT_glBlitFramebuffer(0, 0, static_cast<GLint>(m_width), static_cast<GLint>(m_height), 0, 0, static_cast<GLint>(m_width), static_cast<GLint>(m_height), GL_COLOR_BUFFER_BIT, GL_NEAREST)); glCheck(GLEXT_glBlitFramebuffer(0, 0, static_cast<GLint>(m_width), static_cast<GLint>(m_height), 0, 0, static_cast<GLint>(m_width), static_cast<GLint>(m_height), GL_COLOR_BUFFER_BIT, GL_NEAREST));
glCheck(GLEXT_glBindFramebuffer(GLEXT_GL_DRAW_FRAMEBUFFER, multisampleIter->second)); glCheck(GLEXT_glBindFramebuffer(GLEXT_GL_DRAW_FRAMEBUFFER, multisampleIt->second));
} }
} }

View File

@ -552,7 +552,7 @@ void Shader::setUniform(const std::string& name, const Texture& texture)
if (location != -1) if (location != -1)
{ {
// Store the location -> texture mapping // Store the location -> texture mapping
TextureTable::iterator it = m_textures.find(location); auto it = m_textures.find(location);
if (it == m_textures.end()) if (it == m_textures.end())
{ {
// New entry, make sure there are enough texture units // New entry, make sure there are enough texture units
@ -970,7 +970,7 @@ bool Shader::compile(const char* vertexShaderCode, const char* geometryShaderCod
//////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////
void Shader::bindTextures() const void Shader::bindTextures() const
{ {
TextureTable::const_iterator it = m_textures.begin(); auto it = m_textures.begin();
for (std::size_t i = 0; i < m_textures.size(); ++i) for (std::size_t i = 0; i < m_textures.size(); ++i)
{ {
GLint index = static_cast<GLsizei>(i + 1); GLint index = static_cast<GLsizei>(i + 1);
@ -989,8 +989,7 @@ void Shader::bindTextures() const
int Shader::getUniformLocation(const std::string& name) int Shader::getUniformLocation(const std::string& name)
{ {
// Check the cache // Check the cache
UniformTable::const_iterator it = m_uniforms.find(name); if (auto it = m_uniforms.find(name); it != m_uniforms.end())
if (it != m_uniforms.end())
{ {
// Already in cache, return it // Already in cache, return it
return it->second; return it->second;

View File

@ -39,8 +39,9 @@ namespace
// Convert a string to lower case // Convert a string to lower case
std::string toLower(std::string str) std::string toLower(std::string str)
{ {
for (std::string::iterator i = str.begin(); i != str.end(); ++i) for (char& c : str)
*i = static_cast<char>(std::tolower(*i)); c = static_cast<char>(std::tolower(c));
return str; return str;
} }
} }
@ -119,9 +120,9 @@ std::string Http::Request::prepare() const
out << "HTTP/" << m_majorVersion << "." << m_minorVersion << "\r\n"; out << "HTTP/" << m_majorVersion << "." << m_minorVersion << "\r\n";
// Write fields // Write fields
for (FieldTable::const_iterator i = m_fields.begin(); i != m_fields.end(); ++i) for (const auto& [fieldKey, fieldValue] : m_fields)
{ {
out << i->first << ": " << i->second << "\r\n"; out << fieldKey << ": " << fieldValue << "\r\n";
} }
// Use an extra \r\n to separate the header from the body // Use an extra \r\n to separate the header from the body
@ -154,16 +155,13 @@ m_minorVersion(0)
//////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////
const std::string& Http::Response::getField(const std::string& field) const const std::string& Http::Response::getField(const std::string& field) const
{ {
FieldTable::const_iterator it = m_fields.find(toLower(field)); if (auto it = m_fields.find(toLower(field)); it != m_fields.end())
if (it != m_fields.end())
{ {
return it->second; return it->second;
} }
else
{ static const std::string empty;
static const std::string empty = "";
return empty; return empty;
}
} }

View File

@ -557,8 +557,8 @@ Packet& Packet::operator <<(const std::wstring& data)
// Then insert characters // Then insert characters
if (length > 0) if (length > 0)
{ {
for (std::wstring::const_iterator c = data.begin(); c != data.end(); ++c) for (wchar_t c : data)
*this << static_cast<Uint32>(*c); *this << static_cast<Uint32>(c);
} }
return *this; return *this;

View File

@ -734,8 +734,8 @@ void GlContext::cleanupUnsharedResources()
setActive(true); setActive(true);
// Call the registered destruction callbacks // Call the registered destruction callbacks
for (ContextDestroyCallbacks::iterator iter = contextDestroyCallbacks.begin(); iter != contextDestroyCallbacks.end(); ++iter) for (auto& [callback, ptr] : contextDestroyCallbacks)
iter->first(iter->second); callback(ptr);
// Make the originally active context active again // Make the originally active context active again
if (contextToRestore) if (contextToRestore)

View File

@ -314,16 +314,19 @@ void HIDInputManager::freeUp()
if (m_layoutData != 0) if (m_layoutData != 0)
CFRelease(m_layoutData); CFRelease(m_layoutData);
m_layoutData = 0; m_layoutData = 0;
// Do not release m_layout! It is owned by m_layoutData. // Do not release m_layout! It is owned by m_layoutData.
if (m_manager != 0) if (m_manager != 0)
CFRelease(m_manager); CFRelease(m_manager);
m_manager = 0; m_manager = 0;
for (unsigned int i = 0; i < Keyboard::KeyCount; ++i) for (unsigned int i = 0; i < Keyboard::KeyCount; ++i)
{ {
for (IOHIDElements::iterator it = m_keys[i].begin(); it != m_keys[i].end(); ++it) for (IOHIDElementRef iohidElementRef : m_keys[i])
CFRelease(*it); CFRelease(iohidElementRef);
m_keys[i].clear(); m_keys[i].clear();
} }
@ -364,7 +367,7 @@ bool HIDInputManager::isPressed(IOHIDElements& elements)
// state = true if at least one corresponding HID button is pressed // state = true if at least one corresponding HID button is pressed
bool state = false; bool state = false;
for (IOHIDElements::iterator it = elements.begin(); it != elements.end(); /* noop */) for (auto it = elements.begin(); it != elements.end(); /* noop */)
{ {
IOHIDValueRef value = 0; IOHIDValueRef value = 0;

View File

@ -307,10 +307,12 @@ bool JoystickImpl::open(unsigned int index)
std::sort(m_buttons.begin(), m_buttons.end(), JoystickButtonSortPredicate); std::sort(m_buttons.begin(), m_buttons.end(), JoystickButtonSortPredicate);
// Retain all these objects for personal use // Retain all these objects for personal use
for (ButtonsVector::iterator it(m_buttons.begin()); it != m_buttons.end(); ++it) for (IOHIDElementRef iohidElementRef : m_buttons)
CFRetain(*it); CFRetain(iohidElementRef);
for (AxisMap::iterator it(m_axis.begin()); it != m_axis.end(); ++it)
CFRetain(it->second); for (const auto& [axis, iohidElementRef] : m_axis)
CFRetain(iohidElementRef);
if (m_hat != nullptr) if (m_hat != nullptr)
CFRetain(m_hat); CFRetain(m_hat);
@ -329,16 +331,20 @@ bool JoystickImpl::open(unsigned int index)
void JoystickImpl::close() void JoystickImpl::close()
{ {
AutoreleasePool pool; AutoreleasePool pool;
for (ButtonsVector::iterator it(m_buttons.begin()); it != m_buttons.end(); ++it)
CFRelease(*it); for (IOHIDElementRef iohidElementRef : m_buttons)
CFRelease(iohidElementRef);
m_buttons.clear(); m_buttons.clear();
for (AxisMap::iterator it(m_axis.begin()); it != m_axis.end(); ++it) for (const auto& [axis, iohidElementRef] : m_axis)
CFRelease(it->second); CFRelease(iohidElementRef);
m_axis.clear(); m_axis.clear();
if (m_hat != nullptr) if (m_hat != nullptr)
CFRelease(m_hat); CFRelease(m_hat);
m_hat = nullptr; m_hat = nullptr;
// And we unregister this joystick // And we unregister this joystick
@ -356,8 +362,8 @@ JoystickCaps JoystickImpl::getCapabilities() const
caps.buttonCount = m_buttons.size(); caps.buttonCount = m_buttons.size();
// Axis: // Axis:
for (AxisMap::const_iterator it(m_axis.begin()); it != m_axis.end(); ++it) for (const auto& [axis, iohidElementRef] : m_axis)
caps.axes[it->first] = true; caps.axes[axis] = true;
if (m_hat != nullptr) if (m_hat != nullptr)
caps.axes[Joystick::PovX] = caps.axes[Joystick::PovY] = true; caps.axes[Joystick::PovX] = caps.axes[Joystick::PovY] = true;
@ -416,7 +422,7 @@ JoystickState JoystickImpl::update()
// Update buttons' state // Update buttons' state
unsigned int i = 0; unsigned int i = 0;
for (ButtonsVector::iterator it(m_buttons.begin()); it != m_buttons.end(); ++it, ++i) for (auto it = m_buttons.begin(); it != m_buttons.end(); ++it, ++i)
{ {
IOHIDValueRef value = 0; IOHIDValueRef value = 0;
IOHIDDeviceGetValue(IOHIDElementGetDevice(*it), *it, &value); IOHIDDeviceGetValue(IOHIDElementGetDevice(*it), *it, &value);
@ -432,10 +438,10 @@ JoystickState JoystickImpl::update()
} }
// Update axes' state // Update axes' state
for (AxisMap::iterator it = m_axis.begin(); it != m_axis.end(); ++it) for (const auto& [axis, iohidElementRef] : m_axis)
{ {
IOHIDValueRef value = 0; IOHIDValueRef value = 0;
IOHIDDeviceGetValue(IOHIDElementGetDevice(it->second), it->second, &value); IOHIDDeviceGetValue(IOHIDElementGetDevice(iohidElementRef), iohidElementRef, &value);
// Check for plug out. // Check for plug out.
if (!value) if (!value)
@ -453,13 +459,13 @@ JoystickState JoystickImpl::update()
// This method might not be very accurate (the "0 position" can be // This method might not be very accurate (the "0 position" can be
// slightly shift with some device) but we don't care because most // slightly shift with some device) but we don't care because most
// of devices are so sensitive that this is not relevant. // of devices are so sensitive that this is not relevant.
double physicalMax = IOHIDElementGetPhysicalMax(it->second); double physicalMax = IOHIDElementGetPhysicalMax(iohidElementRef);
double physicalMin = IOHIDElementGetPhysicalMin(it->second); double physicalMin = IOHIDElementGetPhysicalMin(iohidElementRef);
double scaledMin = -100; double scaledMin = -100;
double scaledMax = 100; double scaledMax = 100;
double physicalValue = IOHIDValueGetScaledValue(value, kIOHIDValueScaleTypePhysical); double physicalValue = IOHIDValueGetScaledValue(value, kIOHIDValueScaleTypePhysical);
float scaledValue = (((physicalValue - physicalMin) * (scaledMax - scaledMin)) / (physicalMax - physicalMin)) + scaledMin; float scaledValue = (((physicalValue - physicalMin) * (scaledMax - scaledMin)) / (physicalMax - physicalMin)) + scaledMin;
state.axes[it->first] = scaledValue; state.axes[axis] = scaledValue;
} }
// Update POV/Hat state. Assuming model described in `open`, values are: // Update POV/Hat state. Assuming model described in `open`, values are:

View File

@ -89,10 +89,8 @@ void CloseDisplay(Display* display)
//////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////
Atom getAtom(const std::string& name, bool onlyIfExists) Atom getAtom(const std::string& name, bool onlyIfExists)
{ {
AtomMap::const_iterator iter = atoms.find(name); if (auto it = atoms.find(name); it != atoms.end())
return it->second;
if (iter != atoms.end())
return iter->second;
Display* display = OpenDisplay(); Display* display = OpenDisplay();

View File

@ -125,30 +125,30 @@ namespace
// Since isJoystick returned true, this has to succeed // Since isJoystick returned true, this has to succeed
const char* devnode = udev_device_get_devnode(udevDevice); const char* devnode = udev_device_get_devnode(udevDevice);
JoystickList::iterator record; JoystickList::iterator recordIt;
for (record = joystickList.begin(); record != joystickList.end(); ++record) for (recordIt = joystickList.begin(); recordIt != joystickList.end(); ++recordIt)
{ {
if (record->deviceNode == devnode) if (recordIt->deviceNode == devnode)
{ {
if (std::strstr(action, "add")) if (std::strstr(action, "add"))
{ {
// The system path might have changed so update it // The system path might have changed so update it
const char* syspath = udev_device_get_syspath(udevDevice); const char* syspath = udev_device_get_syspath(udevDevice);
record->plugged = true; recordIt->plugged = true;
record->systemPath = syspath ? syspath : ""; recordIt->systemPath = syspath ? syspath : "";
break; break;
} }
else if (std::strstr(action, "remove")) else if (std::strstr(action, "remove"))
{ {
record->plugged = false; recordIt->plugged = false;
break; break;
} }
} }
} }
if (record == joystickList.end()) if (recordIt == joystickList.end())
{ {
if (std::strstr(action, "add")) if (std::strstr(action, "add"))
{ {
@ -177,8 +177,8 @@ namespace
} }
// Reset the plugged status of each mapping since we are doing a full rescan // Reset the plugged status of each mapping since we are doing a full rescan
for (JoystickList::iterator record = joystickList.begin(); record != joystickList.end(); ++record) for (JoystickRecord& record : joystickList)
record->plugged = false; record.plugged = false;
udev_enumerate* udevEnumerator = udev_enumerate_new(udevContext); udev_enumerate* udevEnumerator = udev_enumerate_new(udevContext);
@ -218,27 +218,27 @@ namespace
// Since isJoystick returned true, this has to succeed // Since isJoystick returned true, this has to succeed
const char* devnode = udev_device_get_devnode(newUdevDevice); const char* devnode = udev_device_get_devnode(newUdevDevice);
JoystickList::iterator record; JoystickList::iterator recordIt;
// Check if the device node has been mapped before // Check if the device node has been mapped before
for (record = joystickList.begin(); record != joystickList.end(); ++record) for (recordIt = joystickList.begin(); recordIt != joystickList.end(); ++recordIt)
{ {
if (record->deviceNode == devnode) if (recordIt->deviceNode == devnode)
{ {
record->plugged = true; recordIt->plugged = true;
break; break;
} }
} }
// If not mapped before, map it now // If not mapped before, map it now
if (record == joystickList.end()) if (recordIt == joystickList.end())
{ {
JoystickRecord nweRecord; JoystickRecord newRecord;
nweRecord.deviceNode = devnode; newRecord.deviceNode = devnode;
nweRecord.systemPath = syspath; newRecord.systemPath = syspath;
nweRecord.plugged = true; newRecord.plugged = true;
joystickList.push_back(nweRecord); joystickList.push_back(newRecord);
} }
} }

View File

@ -143,13 +143,13 @@ bool VulkanImplX11::isAvailable(bool requireGraphics)
bool has_VK_KHR_surface = false; bool has_VK_KHR_surface = false;
bool has_VK_KHR_platform_surface = false; bool has_VK_KHR_platform_surface = false;
for (std::vector<VkExtensionProperties>::const_iterator iter = extensionProperties.begin(); iter != extensionProperties.end(); ++iter) for (const VkExtensionProperties& properties : extensionProperties)
{ {
if (!std::strcmp(iter->extensionName, VK_KHR_SURFACE_EXTENSION_NAME)) if (!std::strcmp(properties.extensionName, VK_KHR_SURFACE_EXTENSION_NAME))
{ {
has_VK_KHR_surface = true; has_VK_KHR_surface = true;
} }
else if (!std::strcmp(iter->extensionName, VK_KHR_XLIB_SURFACE_EXTENSION_NAME)) else if (!std::strcmp(properties.extensionName, VK_KHR_XLIB_SURFACE_EXTENSION_NAME))
{ {
has_VK_KHR_platform_surface = true; has_VK_KHR_platform_surface = true;
} }

View File

@ -1200,9 +1200,9 @@ void WindowImplX11::requestFocus()
{ {
Lock lock(allWindowsMutex); Lock lock(allWindowsMutex);
for (std::vector<WindowImplX11*>::iterator itr = allWindows.begin(); itr != allWindows.end(); ++itr) for (sf::priv::WindowImplX11* windowPtr : allWindows)
{ {
if ((*itr)->hasFocus()) if (windowPtr->hasFocus())
{ {
sfmlWindowFocused = true; sfmlWindowFocused = true;
break; break;
@ -1733,17 +1733,17 @@ bool WindowImplX11::processEvent(XEvent& windowEvent)
if (windowEvent.type == KeyRelease) if (windowEvent.type == KeyRelease)
{ {
// Find the next KeyPress event with matching keycode and time // Find the next KeyPress event with matching keycode and time
std::deque<XEvent>::iterator iter = std::find_if( auto it = std::find_if(
m_events.begin(), m_events.begin(),
m_events.end(), m_events.end(),
KeyRepeatFinder(windowEvent.xkey.keycode, windowEvent.xkey.time) KeyRepeatFinder(windowEvent.xkey.keycode, windowEvent.xkey.time)
); );
if (iter != m_events.end()) if (it != m_events.end())
{ {
// If we don't want repeated events, remove the next KeyPress from the queue // If we don't want repeated events, remove the next KeyPress from the queue
if (!m_keyRepeat) if (!m_keyRepeat)
m_events.erase(iter); m_events.erase(it);
// This KeyRelease is a repeated event and we don't want it // This KeyRelease is a repeated event and we don't want it
return false; return false;

View File

@ -451,9 +451,9 @@ void JoystickImpl::cleanupDInput()
bool JoystickImpl::isConnectedDInput(unsigned int index) bool JoystickImpl::isConnectedDInput(unsigned int index)
{ {
// Check if a joystick with the given index is in the connected list // Check if a joystick with the given index is in the connected list
for (std::vector<JoystickRecord>::iterator i = joystickList.begin(); i != joystickList.end(); ++i) for (const JoystickRecord& record : joystickList)
{ {
if (i->index == index) if (record.index == index)
return true; return true;
} }
@ -472,7 +472,7 @@ void JoystickImpl::updateConnectionsDInput()
HRESULT result = directInput->EnumDevices(DI8DEVCLASS_GAMECTRL, &JoystickImpl::deviceEnumerationCallback, nullptr, DIEDFL_ATTACHEDONLY); HRESULT result = directInput->EnumDevices(DI8DEVCLASS_GAMECTRL, &JoystickImpl::deviceEnumerationCallback, nullptr, DIEDFL_ATTACHEDONLY);
// Remove devices that were not connected during the enumeration // Remove devices that were not connected during the enumeration
for (std::vector<JoystickRecord>::iterator i = joystickList.begin(); i != joystickList.end();) for (auto i = joystickList.begin(); i != joystickList.end();)
{ {
if (!i->plugged) if (!i->plugged)
i = joystickList.erase(i); i = joystickList.erase(i);
@ -490,14 +490,14 @@ void JoystickImpl::updateConnectionsDInput()
// Assign unused joystick indices to devices that were newly connected // Assign unused joystick indices to devices that were newly connected
for (unsigned int i = 0; i < Joystick::Count; ++i) for (unsigned int i = 0; i < Joystick::Count; ++i)
{ {
for (std::vector<JoystickRecord>::iterator j = joystickList.begin(); j != joystickList.end(); ++j) for (JoystickRecord& record : joystickList)
{ {
if (j->index == i) if (record.index == i)
break; break;
if (j->index == Joystick::Count) if (record.index == Joystick::Count)
{ {
j->index = i; record.index = i;
break; break;
} }
} }
@ -523,12 +523,12 @@ bool JoystickImpl::openDInput(unsigned int index)
m_buffered = false; m_buffered = false;
// Search for a joystick with the given index in the connected list // Search for a joystick with the given index in the connected list
for (std::vector<JoystickRecord>::iterator it = joystickList.begin(); it != joystickList.end(); ++it) for (const JoystickRecord& record : joystickList)
{ {
if (it->index == index) if (record.index == index)
{ {
// Create device // Create device
HRESULT result = directInput->CreateDevice(it->guid, &m_device, nullptr); HRESULT result = directInput->CreateDevice(record.guid, &m_device, nullptr);
if (FAILED(result)) if (FAILED(result))
{ {
@ -552,10 +552,10 @@ bool JoystickImpl::openDInput(unsigned int index)
// Check if device is already blacklisted // Check if device is already blacklisted
if (m_identification.productId && m_identification.vendorId) if (m_identification.productId && m_identification.vendorId)
{ {
for (JoystickBlacklist::const_iterator iter = joystickBlacklist.begin(); iter != joystickBlacklist.end(); ++iter) for (const JoystickBlacklistEntry& blacklistEntry : joystickBlacklist)
{ {
if ((m_identification.productId == iter->productId) && if ((m_identification.productId == blacklistEntry.productId) &&
(m_identification.vendorId == iter->vendorId)) (m_identification.vendorId == blacklistEntry.vendorId))
{ {
// Device is blacklisted // Device is blacklisted
m_device->Release(); m_device->Release();

View File

@ -145,13 +145,13 @@ bool VulkanImplWin32::isAvailable(bool requireGraphics)
bool has_VK_KHR_surface = false; bool has_VK_KHR_surface = false;
bool has_VK_KHR_platform_surface = false; bool has_VK_KHR_platform_surface = false;
for (std::vector<VkExtensionProperties>::const_iterator iter = extensionProperties.begin(); iter != extensionProperties.end(); ++iter) for (const VkExtensionProperties& properties : extensionProperties)
{ {
if (!std::strcmp(iter->extensionName, VK_KHR_SURFACE_EXTENSION_NAME)) if (!std::strcmp(properties.extensionName, VK_KHR_SURFACE_EXTENSION_NAME))
{ {
has_VK_KHR_surface = true; has_VK_KHR_surface = true;
} }
else if (!std::strcmp(iter->extensionName, VK_KHR_WIN32_SURFACE_EXTENSION_NAME)) else if (!std::strcmp(properties.extensionName, VK_KHR_WIN32_SURFACE_EXTENSION_NAME))
{ {
has_VK_KHR_platform_surface = true; has_VK_KHR_platform_surface = true;
} }