簡體   English   中英

斷言失敗錯誤,C ++中的向量下標超出范圍問題

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM