断言失败错误,C++中的矢量下标超出范围问题
Assertion Failure Error, vector subscript out of range problem in C++
我的目标是vec
数组设置为数组intData
。我阅读了这个问题并将其应用于我的代码。在执行该过程之前,我调整了 intData 的大小。在 C# 中,这种intData = GetIntArrayFromByteArray(vec);
不会产生任何问题,但是当涉及到C++中的数组向量时,我很困惑。我说明了我在哪里得到错误作为评论。我尝试调整大小,但没有用。有人可以帮我吗?
代码解释;
-
buf
收到一条消息(它不为空,我从客户端收到消息( -
我创建了一个与
buf
大小相同的矢量数组vec
-
GetIntArrayFromCharArray()
将字符矢量数组转换为 int 数组 向量。char buf[1550];//message gets here not empty vector<uint16_t> intData; //empty int vector //char buf ----> vecor<char> vec int n = sizeof(buf) / sizeof(buf[0]); vector<char> vec(buf, buf + n); intData.resize(vec.size());//here I resize /* irrelevant code piece runs here */ if (something == 1)// First fragment { intData = GetIntArrayFromCharArray(vec);//size out of range error here }
这是GetIntArrayFromCharArray()
进行转换
vector<uint16_t> GetIntArrayFromCharArray(vector<char> arr)
{
// If the number of bytes is not even, put a zero at the end
if ((arr.size() % 2) == 1)
arr.resize(arr.size()+1);
arr.push_back(0);
vector<uint16_t> intArray;
for (int i = 0; i < arr.size(); i += 2)
intArray.push_back((uint16_t)((arr[i] << 8) | arr[i + 1]));
return intArray;
}
// If the number of bytes is not even, put a zero at the end
if ((arr.size() % 2) == 1)
arr.resize(arr.size()+1);
arr.push_back(0);
哎 呦!
这实际上是:
- "如果字节数不均匀,则在末尾加一个零">
- "然后总是在最后再加一个零">
结果是,您将始终拥有奇数个元素。这会在您尝试读取一个经过向量末尾的循环时中断后续循环。
我不认为你的意思是把那个push_back
放在那里,或者你的意思是让它而不是resize
电话。
顺便说一下,正如 Jarod 指出的那样,预先调整intData
大小完全是浪费时间,因为您使用它做的下一件事(据我们所知(是替换整个向量。
相关文章:
- 尝试通过多个向量访问变量时,向量下标超出范围
- 矢量下标超出SFML游戏中的范围
- 如何在C++程序中使用下标数字?
- 一组值的零开销下标运算符
- 运行时错误:矢量下标超出范围:正在检查空集
- 如何重载下标运算符 [] 以引用 2d STL 数组?
- 如果变量数据包含大于 vector 所有元素的整数,则仅在视觉工作室上接收"矢量下标超出范围"?
- 矢量无效下标.SFML
- C++ IDE 不会推断/自动完成对模板类中的 std::array 下标表达式的成员访问
- 编译期间矢量下标超出范围
- C++ 调试断言失败 - 矢量下标超出视觉工作室的范围
- 有什么理由不扩展 std::set 以添加下标运算符吗?
- 在继承的模板类中使用下标 [] 运算符
- 对矢量来说是全新的.矢量下标超出范围
- 断言失败错误,C++中的矢量下标超出范围问题
- Stroustrup的代码审查-编程原理-Ch-4-问题:3-错误:矢量下标超出范围
- C++矢量下标问题
- 这段代码有什么问题?我无法从文件中读取矢量。表达式:矢量下标超出范围
- 下标操作符重载:返回引用问题
- 对于原始数组和std::vector,明显没有对下标进行过一次结束的说明.这个问题已经得到了决定性的解决吗?