[英]Assertion Failure Error, vector subscript out of range problem in C++
My aim is to set vec
array to intData
array. 我的目的是将
vec
数组设置为intData
数组。 I read this question and applied it to my code. 我阅读了此问题并将其应用于我的代码。 I resized intData before doing the process.
在执行该过程之前,我调整了intData的大小。 In C# this
intData = GetIntArrayFromByteArray(vec);
在C#中,此
intData = GetIntArrayFromByteArray(vec);
creates no problem but I am confused when it comes to array vectors in C++. 不会造成任何问题,但是对于C ++中的数组矢量,我感到困惑。 I stated where I get the error as a comment.
我说出我在哪里得到的错误作为评论。 I tried resizing but it didn't work.
我尝试调整大小,但是没有用。 Can someone help me please?
有人能帮助我吗?
Code explanation; 代码说明;
buf
gets a message( it is not empty I get message from client ) buf
收到一条消息( 它不是空的,我从客户端收到消息 )
I create a vector array vec
same size as buf
我创建一个与
buf
大小相同的向量数组vec
GetIntArrayFromCharArray()
converts char vector array into int array vector. GetIntArrayFromCharArray()
将char向量数组转换为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 }
This is GetIntArrayFromCharArray()
does the conversion 这是
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);
Whoops! 哎呀!
This is actually: 这实际上是:
The consequence is that you will always have an odd number of elements. 结果是您将总是具有奇数个元素。 This breaks the subsequent loop as you try to read one past the end of the vector.
当您尝试读取向量结尾之后的内容时,这会中断随后的循环。
I don't think you meant to put that push_back
there, or perhaps you meant to have it instead of the resize
call. 我不认为你的意思是把那个
push_back
那里,或者你打算把它代替的resize
调用。
By the way, as Jarod pointed out, resizing intData
up-front is a complete waste of time since the next thing you do with it (as far as we can see) is to replace the whole vector. 顺便提一句,正如Jarod所指出的那样,
intData
调整intData
大小完全是浪费时间,因为您下一步要做的(据我们所知)是替换了整个向量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.