我正在制作一个从下到上的 rgb 像素阵列到从上到下。我已经检查了某些东西的值(value),它给了我预期的输出。没有值大于 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;
}
关于C++ Vector 下标超出范围(但事实并非如此),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20463005/