我的目标是将vec
数组设置为intData
数组。我读了this question并将其应用于我的代码。我在执行此过程之前调整了 intData 的大小。在 C# 中,此 intData = GetIntArrayFromByteArray(vec);
不会产生任何问题,但当涉及到 C++ 中的数组 vector 时,我感到很困惑。我说明了我在哪里得到错误作为评论。我尝试调整大小,但没有用。有人可以帮帮我吗?
代码解释;
buf
得到一个消息(它不是空的我从客户端得到消息)我创建了一个与
大小相同的 vector 数组buf
vec
GetIntArrayFromCharArray()
将 char vector 数组转换为 int 数组 vector 。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);
糟糕!
这实际上是:
- “如果字节数不是偶数,则在末尾补零”
- “然后总是在末尾再放一个零”
结果是您总是有奇数个元素。当您尝试读取 vector 末尾之后的循环时,这会中断后续循环。
我不认为您打算将 push_back
放在那里,或者您可能打算用它代替 resize
调用。
顺便说一下,正如 Jarod 指出的那样,预先调整 intData
的大小完全是浪费时间,因为您接下来要做的事情(据我们所知)是替换全 vector 。
关于c++ - Assertion Failure Error,C++中vector subscript out of range问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57758306/