Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: I found a range-based for loop issue with vs2012  (Read 228 times)

0 Members and 1 Guest are viewing this topic.

hdsiria

  • Newbie
  • *
  • Posts: 20
    • View Profile
I found a range-based for loop issue with vs2012
« 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
« Last Edit: December 19, 2023, 04:21:20 am by hdsiria »

kimci86

  • Full Member
  • ***
  • Posts: 123
    • View Profile
Re: I found a range-based for loop issue with vs2012
« Reply #1 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);
}

hdsiria

  • Newbie
  • *
  • Posts: 20
    • View Profile
Re: I found a range-based for loop issue with vs2012
« Reply #2 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.