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

Author Topic: Sorting a vector of rectangles  (Read 93 times)

0 Members and 1 Guest are viewing this topic.

Daniel

  • Newbie
  • *
  • Posts: 6
    • View Profile
    • Email
Sorting a vector of rectangles
« on: July 13, 2020, 11:38:55 am »
Hello!

So I'm trying to implement bubble sort algorithm. I've created a vector in which I'm appending some rectangles and I'll sort them by their heights but it doesn't seem to sort anything. Am I doing something wrong? Please test this code... it's not too much.

#include <SFML/Graphics.hpp>
#include <ctime>
#include <iostream>
#include <vector>

int main()
{
    srand(time(0));
    float randomHeight;
    std::vector<sf::RectangleShape> v;
    float currY = 100;
    sf::RenderWindow window(sf::VideoMode(1280, 800), "SFML works!");
   
    for (unsigned int i = 0; i < 100; i++)
    {
       
        randomHeight = rand() % 500 + 200;
        sf::RectangleShape rect({ 4, randomHeight });
        rect.setFillColor(sf::Color::White);
        rect.setRotation(180);
        currY += 10;
        rect.setPosition({ currY, 720 });

        v.push_back(rect);
    }
 

    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }
       
       
       
        for (unsigned int i = 0; i < v.size(); i++)
        {
            for (auto itj = v.begin(); itj != v.end() - 1; itj = std::next(itj))
            {
                if ((*itj).getSize().y > (*std::next(itj)).getSize().y)
                {
                    std::swap(*itj, *std::next(itj));
                }
            }
        }

        for (auto i = v.begin(); i != v.end(); i = std::next(i))
            window.draw(*i);
        window.display();
       
       
    }
   
    return 0;
}
« Last Edit: July 13, 2020, 11:45:00 am by Daniel »

G.

  • Hero Member
  • *****
  • Posts: 1454
    • View Profile
🍛
« Reply #1 on: July 13, 2020, 02:18:26 pm »
They are swapped in the vector, but their coordinates are never modified so you won't see any difference when you draw them.

Daniel

  • Newbie
  • *
  • Posts: 6
    • View Profile
    • Email
Re: Sorting a vector of rectangles
« Reply #2 on: July 13, 2020, 05:01:17 pm »
Yeah... I found out that later. Thanks!

Hapax

  • Hero Member
  • *****
  • Posts: 2999
  • My number of posts is shown in hexadecimal.
    • View Profile
Re: Sorting a vector of rectangles
« Reply #3 on: July 13, 2020, 11:34:50 pm »
It will affect the order they are drawn, which you need to be aware of when objects overlap.

Also, don't forget to clear the window each time :P
Selba Ward - SFML drawables
Kairos - Timing Library
Rectangular Boundary Collision - Rectangular SAT Collision

@Hapaxiation - Hapaxia on Twitter