C ++ Vector下标超出范围(但不是)

时间:2013-12-09 04:09:47

标签: c++ vector range

我正在制作一个底部的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;
}

2 个答案:

答案 0 :(得分:1)

您应该可以用以下内容替换整个功能:

#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;
}

答案 1 :(得分:0)

如果您需要编写自己的版本反向:

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