[英]Assertion Failure Error, vector subscript out of range problem in C++
我的目的是將vec
數組設置為intData
數組。 我閱讀了此問題並將其應用於我的代碼。 在執行該過程之前,我調整了intData的大小。 在C#中,此intData = GetIntArrayFromByteArray(vec);
不會造成任何問題,但是對於C ++中的數組矢量,我感到困惑。 我說出我在哪里得到的錯誤作為評論。 我嘗試調整大小,但是沒有用。 有人能幫助我嗎?
代碼說明;
buf
收到一條消息( 它不是空的,我從客戶端收到消息 )
我創建一個與buf
大小相同的向量數組vec
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 }
這是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
調整intData
大小完全是浪費時間,因為您下一步要做的(據我們所知)是替換了整個向量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.