简体   繁体   中英

I can't find where the error occurred when using vector

When I run this code, I can get the Debug Assertion Failed error.

"Expression: vector erase iterator outside range"

I can't find where the error occurred.

for (int i = 0; i < comb.size(); i++) {
        if (couple.size() != 0 && couple.size() == mate * 2) {
            vector<int>::iterator iter = couple.begin();
            int rad = rand() % couple.size();
            rad = (rad % 2 == 0 ? rad : rad + 1);
            iter += rad;
            iter = couple.erase(iter);
            iter = couple.erase(iter);
        }
        couple.push_back(comb[i]);
        printf("%d ", comb[i]);
    }
  • Let's assume couple.size() == 6 .
  • Let's assume rad == 5 .
  • Then rad will be transformed to 6.
  • Then you will call erase() on an iterator past the end of the array. Which is illegal.

I'm going to guess that you should have done:

rad = (rad % 2 == 0 ? rad : rad - 1);

But it's hard to say since you never explained what you're trying to accomplish.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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