SFML community forums

Help => General => Topic started by: hdsiria on December 19, 2023, 04:16:09 am

Title: I found a range-based for loop issue with vs2012
Post by: hdsiria on December 19, 2023, 04:16:09 am
I'm using VertexArray to draw a tilemap
        virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const
        {
                // apply the transform
                states.transform *= getTransform();
                //Range-based for loop is used here, compiling with vs2012 and running with a high cpu usage of 30%,so one cpu core is at full load
                //but threre is no problem with vs2013
                //for (auto content:m_verticesAndTexture){
                //      states.texture = &content.second;
                //      target.draw(content.first, states);
                //}
                //Use the classic for loop instead,The cpu usage returned to normal after compiling with vs2012
                for(int i=0;i<m_verticesAndTexture.size();i++){
                        states.texture = &m_verticesAndTexture[i].second;
                        target.draw(m_verticesAndTexture[i].first, states);
                }

        }
 
I don't think vs2012 supports c++11 very well
Title: Re: I found a range-based for loop issue with vs2012
Post by: kimci86 on December 19, 2023, 07:12:44 am
The range-based for loop in comments is copying each item to use it in the the loop body.
You probably want to use a reference to each item with type auto& instead of a copy with type auto.
It looks like a const reference would also be possible with const auto&.

Try this:
for (const auto& content : m_verticesAndTexture)
{
    states.texture = &content.second;
    target.draw(content.first, states);
}

If you can enable c++17, you could use structured bindings to make this more readable:
for (const auto& [vertices, texture] : m_verticesAndTexture)
{
    states.texture = &texture;
    target.draw(vertices, states);
}
Title: Re: I found a range-based for loop issue with vs2012
Post by: hdsiria on December 19, 2023, 07:32:28 am
Thank you, it is true, I tried the const reference and now the cpu usage is normal using Range-based for loop.