C++ 矢量下标超出范围(但事实并非如此)
C++ Vector subscript out of range (but it's not)
我正在制作一个从下到上的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
。
相关文章:
- 伪造事实↔false
- 为什么右值不能绑定到非常量左值引用,除了写入临时无效的事实?
- 如何在CLIPS中优化不同模板事实之间的模式匹配
- 无法在剪辑嵌入式应用程序中断言事实
- 生成(并非如此)出现特定字符串的随机字符串
- 链表显示;缺少..但事实并非如此
- C++ 通过引用传递单个元素数组 - 这是事实吗?
- C++ 矢量下标超出范围(但事实并非如此)
- 视觉C++将其视为常量,而事实并非如此
- C++前缀增量运算符返回左值这一事实的实际用法
- 此代码看起来像是删除了此对象,但事实并非如此
- C++ "warning: returning reference to temporary " - 但事实并非如此
- MSG类型背后的事实
- Json chuck事实解析
- 我的类主要是容器的前端,我应该公开这个事实吗
- 有什么方法可以解决 c++ 不支持运行时模板的事实吗?
- 利用vector的元素存储在堆中的事实
- 转化会失去限定符,但实际上并非如此
- 为什么is_constructible声称某物是可构造的,而实际上并非如此?
- 从 C/C++ 调用 Prolog 时将事实传达给 Prolog(不使用断言)