std::vector.size() 不起作用
我有一些涉及某些向量的代码,但它拒绝给我向量的大小:
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();
有什么原因吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
矢量的
operator[]
不进行边界检查。因此,会发生以下情况:如果在关键字向量中找不到您的
word
,则x
将是关键字的大小。一次一块:
keywords[x]
现在读取超出向量末尾的内容,返回垃圾。.get_stats()
尝试返回一个向量,但只是得到更多的垃圾。现在,您正在对本质上损坏的数据调用函数。
要解决此问题,请检查
x <在
之前,或者只使用vector::operator[]
中使用 keywords.size()vector::at()
进行边界检查。vector's
operator[]
does not do bounds checking. So, here's what happens:if this doesn't find your
word
in the keywords vector,x
will be the size of keywords.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.Now you're calling a function on what is essentially corrupt data.
To fix this, check for
x < keywords.size()
before you use it invector::operator[]
-- or just usevector::at()
which does do bounds checking.