簡體   English   中英

std :: vector.size()不起作用

[英]std::vector.size() not working

我有一些涉及某些向量的代碼,但是它拒絕給我向量的大小:

using namespace std;

struct key_stat{
    string USER, url;
    float click_count, post_count, click_cost, post_cost;
    keyword_stat(): USER("") {}
};

class key
{
    private:
    string word;
    vector <key_stat> stats;
public:
    key(string & kw);
    vector <key_stat> get_stats(){return stats;}

};


// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void search(string & word, vector <key> & keys){
    unsigned int x;
    // getting the x value
    for (x = 0; x < keys.size(); x++){
        if (keys[x].get_word() == word)
            break;
    }
    vector <keyword_stat> t = keys[x].get_stats();
    t.size()
}

這不起作用:

t.size(); 

有什么原因嗎?

vector的operator[]不進行邊界檢查。 因此,會發生以下情況:

for (x = 0; x < keywords.size(); x++){
    if (keywords[x].get_word() == word)
        break;
}

如果在關鍵字向量中找不到您的word ,則x為關鍵字的大小。

vector <keyword_stat> t = keywords[x].get_stats();

一次一段: keywords[x]現在讀到向量的末尾,返回垃圾。 .get_stats()嘗試返回向量,但是只會得到更多的垃圾。

t.size();

現在,您正在對本質上是損壞的數據的函數進行調用。

要解決此問題,請在vector::operator[]使用x < keywords.size()之前進行檢查-或僅使用進行邊界檢查的vector::at()

暫無
暫無

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

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