简体   繁体   中英

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. 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.

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. .get_stats() attempts to return a vector, but is just getting more garbage.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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