簡體   English   中英

C++ 向量 push_back 沒有復制?

[英]C++ vector push_back not making a copy?

vector<minHeap> letters;
letters = countLetters(text);

while (letters.size() >= 2) {
    minHeap first = popMin(&letters);
    minHeap second = popMin(&letters);
    minHeap third('$');

    third.count = first.count + second.count;
    third.left = &first;
    third.right = &second;
    letters.push_back(third);
}

我試圖調試代碼。 “第一”、“第二”和“第三”值工作正常。 我的問題是:當我將“第三”推入向量時,在下一輪循環中,我們在上一輪推入的 object 更改為新的“第三”,並且與“第三”相同新一輪。

例如在第一輪 X 被推入向量中,在下一輪 Y 被推入,但問題是它也將 X 更改為 Y,所以我們現在有 2 個 Y。 在下一輪中,我們再次獲得 3 Z。

就像它沒有創建“第三個”的副本一樣,所以當我更改它時,它也會更改以前的對象。

我究竟做錯了什么? :秒

編輯:

最小堆 class:

class minHeap {
public:
    char letter;
    int count = 1;
    minHeap* left = NULL;
    minHeap* right = NULL;

    minHeap(char letter) {
        this->letter = letter;
    }
};

popMin:(在 minHeaps 中找到最小的 'count' 並銷毀它,然后返回它的副本)

minHeap popMin(vector<minHeap>* letters) {
    int index = 0;
    for (size_t i = 0; i < letters->size(); i++) {
        if (letters->at(i).count < letters->at(index).count)
            index = i;
    }
    minHeap res = letters->at(index);
    letters->erase(letters->begin() + index);
    return res;
}

countLetters:(計算字母並為每個字母創建一個 minHeap object,如果之前創建,則增加“計數”(頻率)。

vector<minHeap> countLetters(string text) {
    vector<minHeap> letters; // Stores all the characters with their count
    for (size_t i = 0; i < text.length(); i++) {
        bool found = false;
        for (size_t j = 0; j < letters.size(); j++) {
            if (letters.at(j).letter == text[i]) {
                letters.at(j).count++; // Character exists in list, increase its count by one
                found = true;
                break;
            }
        }
        if (!found) { // Character doesn't exist in list, create it and push it to the list
            minHeap letter(text[i]);
            letters.push_back(letter);
        }
    }

    return letters;
}

一般來說:我正在嘗試使用 minHeap 進行霍夫曼編碼。

您正在存儲 &first 和 &second,當當前迭代結束時,它們成為無效指針。 如果在此之后取消引用它們,則您的程序具有未定義的行為。 @molbdnilo

所以我將代碼更改為:

vector<minHeap> letters;
    letters = countLetters(text);

    
    while (letters.size() >= 2) {
        minHeap* first = new minHeap('-');
        *first = popMin(&letters);

        minHeap* second = new minHeap('-');
        *second = popMin(&letters);

        minHeap third('$');

        third.count = first->count + second->count;
        third.left = first;
        third.right = second;
        letters.push_back(third);
    }

它是固定的。 謝謝:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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