C++ 矢量下标超出范围(但事实并非如此)

C++ Vector subscript out of range (but it's not)

本文关键字:事实 并非如此 范围 下标 C++      更新时间:2023-10-16

我正在制作一个从下到上的rgb像素阵列。我检查了一些东西的值,它给了我预期的输出。没有值大于obj.size(),也没有值小于0,我不知道发生了什么:/

std::vector<std::string> BMP_READER::TopBottom(std::vector<std::string> obj)
{
    if (y_height <= 1) { return obj; } // nothing to reverse if its only one row 
    std::vector<std::string> new_v;
    for (int h = 0; h < y_height; h++)
    {
        for (int i = x_width; i >= 1; i--)
        {
            int something = (obj.size() - i) - (x_width*h); // error
            std::string val = obj[something];
            new_v.push_back(val);
        }
    }
    return new_v;
}

您应该能够将整个函数替换为:

#include <algorithm>
std::vector<std::string> BMP_READER::TopBottom(std::vector<std::string> obj)
{
    std::reverse(obj.begin(), obj.end());
    return obj;
}

请注意,这将使左下角位于右上角。代码中的这一行建议您只想从上到下镜像:

if (y_height <= 1) { return obj; } // nothing to reverse if its only one row 

如果你想交换行,但保持像素从左到右在每一行,那么应该做以下事情:

#include <algorithm>
std::vector<std::string> BMP_READER::TopBottom(std::vector<std::string> obj)
{
    int top_row = 0, bot_row = y_height - 1;
    while (top_row < bot_row)
    {
        std::swap_ranges( obj.begin() + top_row * x_width,
                          obj.begin() + top_row * (x_width + 1),
                          obj.begin() + bot_row * x_width );
        top_row++;
        bot_row--;
    }
    return obj;
}

如果需要编写自己版本的reverse:

std::vector<std::string> BMP_READER::TopBottom(std::vector<std::string> obj)
{
    for (std::size_t i = 0; i < obj.size() / 2; ++i)
    {
        std::swap(obj[i], obj[obj.size() - i - 1]);
    }
    return obj;
}

这是一个只遍历一半元素的for循环。

否则,请使用std::reverse