简体   繁体   English

读取向量迭代器访问错误

[英]Bad access on reading vector iterator

I have a vector<int> called pitches . 我有一个叫做pitchesvector<int> I'm getting periodic bad access on the last line below: 我在下面的最后一行经常遇到bad access

int play = 0;
bool didFind = 0;
vector<int>::const_iterator iterator;

for (iterator = pitches.begin(); iterator != pitches.end(); ++iterator) {
    if (*iterator > lastpitch) { // lastpitch is an int
        didFind = 1;
        play = *iterator;
        break;
    }
}

if (!didFind) play = *(pitches.begin()); // this line gives me bad access

I had previously tried *pitches.begin() on the last line but that always provided bad access and I understand that now. 我之前曾在最后一行尝试过*pitches.begin() ,但始终提供了错误的访问权限,现在我知道了。 But while I get it less often now, this play=*(pitches.begin()); 但是,虽然我现在越来越少了,但是这个play=*(pitches.begin()); is still doing the same occasionally. 偶尔仍然会做同样的事情。 I cannot see anything in the above that would cause that, any suggestions appreciated. 我看不到任何会导致上述问题的内容,任何建议都值得赞赏。

If pitches vector has size 0 , the things inside 如果pitches向量的大小为0 ,则其中的东西

      for (iterator=pitches.begin();iterator!=pitches.end();++iterator)

doesn't get executed and therefore didFind=0 . 没有执行,因此didFind=0

The statement inside if is evaluated. if的语句if被评估。 Yet pitches is empty means pitches.begin()==pitches.end() . 然而pitches是空的手段pitches.begin()==pitches.end() Dereferencing a pitches.end() is to access out of bound and therefore gives bad access . pitches.end()引用pitches.end()会导致访问超出范围,因此会导致访问bad access

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

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