仅在清除后才在向量的向量上崩溃
我对这段代码有一个问题:它总是崩溃,但是当我评论时: dataResults[i].clear();
知道原因吗?
std::vector<std::string> r_OCRtoRetrieve;
std::vector<std::string> DBentries;
//stuff..
int distance = 9999; //TODO change here
int minDistance = 9999;
for(int i=0; i< r_OCRtoRetrieve.size(); i++)
for(int j=0; j< DBentries.size(); j++)
{
distance = calcDistance( (const char *)r_OCRtoRetrieve[i].c_str(),(const char *) DBentries[j].c_str());
if (distance == minDistance)
dataResults[i].push_back(DBentries[j]);
else
if(distance < minDistance)
{
minDistance = distance;
dataResults[i].clear();
dataResults[i].push_back(DBentries[j]);
}
}
编辑:
发现错误..我必须初始化它..这是代码:
for(int i=0; i< r_OCRtoRetrieve.size(); i++)
{
dataResults.push_back(std::vector<std::string>());
for(int j=0; j< DBentries.size(); j++)
{
distance = calcDistance( (const char *)r_OCRtoRetrieve[i].c_str(),(const char *) DBentries[j].c_str());
if (distance == minDistance)
dataResults[i].push_back(DBentries[j]);
else
if(distance < minDistance)
{
minDistance = distance;
if(dataResults[i].size() > 0)
dataResults[i].clear();
dataResults[i].push_back(DBentries[j]);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
向量
dataResults
的大小可能小于i
的某个值probably, the size of your vector
dataResults
is smaller than a certain value ofi
如果您遇到 index out of range 异常,可能是因为您的索引
i
超出了向量dataResults
的范围(如果不是的话)很明显,如果
i
大于dataResults.size()
,那么dataResults[i].clear();
将抛出异常。编辑:
考虑用 STL 迭代器替换基于索引的循环,并用 C++ 样式转换替换 c 样式转换。您的 if 语句也可以重新审视...
编辑 2:
猜测可能的问题,因为您没有告诉我们异常是什么,但您有一个
vector>
对吗?如果是这样,您需要在调用方法或构造循环之前检查正在索引到有效位置的内容,以免索引超出范围。像这样的事情:
老实说,我可能会做更多这样的事情:
If you're getting an index out of range exception it's probably because your index
i
is out of range of the vectordataResults
If that wasn't obvious enough basically if
i
is greater thandataResults.size()
thendataResults[i].clear();
will throw an exception.Edit:
Consider replacing your index based loops with STL iterators and replacing your c-style casting with C++ style casting. Your if statement could be revisited as well ...
Edit 2:
Was a guessing at a likely problem as you didn't tell us what the exception was but you have a
vector<vector<string>>
right? If so you need to check what you are indexing into a valid position before calling methods or construct your loop so that it will not index out of bounds.Something like so:
Honestly I'd probably do something more along the lines of this:
当您开始时,DataResults 中有什么?任何事物?如果不是,那么第一次通过时,当距离小于 9999 时,代码将尝试清除第一个、第零个索引处不存在的位置并抱怨。
如果您进行调试构建,您应该会收到一条有意义的消息。
What is in DataResults when you start? Anything? If not, then then the first time through, when distance is anything less than 9999 then the code will attempt to clear a nonexistent location at the first, zeroth index and complain.
If you do a debug build, you should get a meaningful message.