阅读矢量迭代器上的访问不良

时间:2013-02-18 02:36:52

标签: c++ vector iterator

我有vector<int>名为pitches。我在下面的最后一行定期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

我之前在最后一行尝试了*pitches.begin(),但总是提供了糟糕的访问权限,我现在明白了。但是,虽然我现在不那么频繁,但play=*(pitches.begin());偶尔也会这样做。我不能在上面看到任何会导致这种情况的内容,任何建议都值得赞赏。

1 个答案:

答案 0 :(得分:4)

如果pitches向量的大小为0,则内容为

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

未执行,因此didFind=0

评估if内的语句。但pitches为空,表示pitches.begin()==pitches.end()。取消引用pitches.end()是为了访问越界,因此提供bad access