You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用for循环生成并绘制随机数量与高度的SFML矩形(排序可视化器)

SFML排序可视化器:随机矩形生成问题解答

你的思路方向是对的,但代码里有几个关键错误,而且缺少随机生成的核心逻辑,下面给你梳理问题和修正方案:

现有代码的问题

  • 向量声明错误:std::vector<Bars>写法错误,Bars是你创建的单个矩形对象名,向量的类型应该是sf::RectangleShape,正确写法是std::vector<sf::RectangleShape> bars;
  • 循环逻辑错误:bars.size要改成bars.size()(这是成员函数,不是属性),而且你循环里绘制的是同一个固定的Bars对象,应该绘制向量里的每个元素bars[i]
  • 缺少随机生成逻辑:目前只创建了一个固定大小的矩形,没有生成随机数量、随机高度的矩形填充到向量中

正确的实现方案

下面是完整的可运行代码,包含随机数量、随机高度矩形的生成和绘制逻辑:

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

int main() {
    sf::RenderWindow window(sf::VideoMode(800, 600), "排序可视化器");
    srand(time(nullptr)); // 初始化随机种子,保证每次运行随机结果不同

    // 定义矩形的固定参数
    const int barWidth = 10;
    const int barSpacing = 2; // 矩形之间的间距,避免重叠
    const int minBarHeight = 50; // 矩形最小高度
    const int maxBarHeight = window.getSize().y - 20; // 矩形最大高度,留一点底部边距

    // 随机生成矩形数量(范围:10-50个)
    int barCount = rand() % 41 + 10;

    std::vector<sf::RectangleShape> bars;
    bars.reserve(barCount); // 预分配内存,提升性能

    // 循环生成每个随机矩形
    for (int i = 0; i < barCount; ++i) {
        // 生成随机高度
        int randomHeight = rand() % (maxBarHeight - minBarHeight + 1) + minBarHeight;
        sf::RectangleShape bar(sf::Vector2f(barWidth, randomHeight));
        bar.setFillColor(sf::Color(173, 216, 230));

        // 计算矩形位置:x从左侧20px开始,每个矩形间隔barWidth+barSpacing;y让矩形底部对齐窗口底部
        float xPos = 20 + i * (barWidth + barSpacing);
        float yPos = window.getSize().y - randomHeight;
        bar.setPosition(xPos, yPos);

        bars.push_back(bar); // 将矩形加入向量
    }

    // 主循环
    while (window.isOpen()) {
        sf::Event event;
        while (window.pollEvent(event)) {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        window.clear(sf::Color::Black);
        // 绘制所有矩形
        for (const auto& bar : bars) {
            window.draw(bar);
        }
        window.display();
    }

    return 0;
}

关键逻辑说明

  • 随机种子初始化:srand(time(nullptr))用当前时间作为随机种子,避免每次运行生成完全相同的矩形序列
  • 随机数量控制:rand() % 41 +10可以生成10到50之间的随机整数,你可以根据窗口大小调整这个范围
  • 位置计算:通过i * (barWidth + barSpacing)保证每个矩形横向不重叠,yPos = 窗口高度 - 矩形高度让所有矩形底部对齐,更符合排序可视化的视觉习惯
  • 绘制循环:使用范围for循环for (const auto& bar : bars)遍历向量绘制,比普通for循环更简洁,也可以替换成for(int i=0; i<bars.size(); i++) window.draw(bars[i]);

内容的提问来源于stack exchange,提问作者Milo Becker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 21:03:30