简体   繁体   English

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

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

I have some code involving some vectors, but it refuses to give me the size of the vector: 我有一些涉及某些向量的代码,但是它拒绝给我向量的大小:

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()
}

This does not work: 这不起作用:

t.size(); 

Is there any reason why? 有什么原因吗?

vector's operator[] does not do bounds checking. vector的operator[]不进行边界检查。 So, here's what happens: 因此,会发生以下情况:

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

if this doesn't find your word in the keywords vector, x will be the size of keywords. 如果在关键字向量中找不到您的word ,则x为关键字的大小。

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

a piece at a time: keywords[x] now reads beyond the end of the vector, returning garbage. 一次一段: keywords[x]现在读到向量的末尾,返回垃圾。 .get_stats() attempts to return a vector, but is just getting more garbage. .get_stats()尝试返回向量,但是只会得到更多的垃圾。

t.size();

Now you're calling a function on what is essentially corrupt data. 现在,您正在对本质上是损坏的数据的函数进行调用。

To fix this, check for x < keywords.size() before you use it in vector::operator[] -- or just use vector::at() which does do bounds checking. 要解决此问题,请在vector::operator[]使用x < keywords.size()之前进行检查-或仅使用进行边界检查的vector::at()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM