这个嵌套循环C++有什么问题?

What's wrong with this C++ nested for loop?

本文关键字:什么 问题 C++ 嵌套循环      更新时间:2023-10-16
for (int pixel = 0; pixel < imgVector.size(); pixel++)
{
    for (int x = 0; x < image.getSize().x; x++)
    {
        for (int y = 0; y < image.getSize().y; y++)
        {
            pulledImage.setPixel(x, y, sf::Color::Color(imgVector.at(pixel)));
            pixel++;
        }
    }
}

所以在这个代码中,我试图循环一个向量并使用SFML将其内容放入图像中,但是除非我有pixel++;放在循环内部它会被卡住,我觉得有pixel++;在循环中是不正确的,可能会导致我的程序出现问题。任何帮助不胜感激!

pixel递增太多倍,最终使用越界索引访问imageVector

for (int pixel = 0; pixel < imgVector.size(); pixel++)
{
    for (int x = 0; x < image.getSize().x; x++)
    {
        for (int y = 0; y < image.getSize().y; y++)
        {
            pulledImage.setPixel(x, y, sf::Color::Color(imgVector.at(pixel)));
            // This line does not make sense.
            // Why do you need to increment pixel here?
            pixel++;
        }
    }
}

我猜你需要这样的东西:

size_t pixel = 0;
for (int x = 0; x < image.getSize().x; x++)
{
   for (int y = 0; y < image.getSize().y; y++, ++pixel)
   {
      assert(pixel < imgVector.size());
      pulledImage.setPixel(x, y, sf::Color::Color(imgVector.at(pixel)));
   }
}

您应该记住,sf::Image::setPixel()并不是真正用于更新整个映像的。您不断锁定/解锁数据,与直接访问相比,数据的性能会很差。

如果您想从原始图像数据创建sf::Image,我建议您改用sf::Image::create()重载之一:

sf::Image image;
image.create(width, height, reinterpret_cast<sf::Uint8*>(&imgVector[0]));

这应该创建一个包含所有图像数据的新映像。 widthheight必须具有适当的尺寸。