Reputation: 9001
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?
Upvotes: 1
Views: 6402
Reputation: 9172
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.
Upvotes: 3