【问题标题】:I can't find where the error occurred when using vector使用矢量时找不到错误发生的位置
【发布时间】:2021-04-12 21:49:58
【问题描述】:

当我运行这段代码时,我会得到 Debug Assertion Failed 错误。

“表达式:向量擦除迭代器超出范围”

我找不到错误发生的位置。

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]);
    }

【问题讨论】:

  • 你为什么用printf()而不是std::cout?
  • 据我所知,printf() 更快。

标签: c++ vector iterator


【解决方案1】:
  • 假设couple.size() == 6。
  • 假设rad == 5。
  • 然后rad 将被转换为 6。
  • 然后,您将在数组末尾之后的迭代器上调用 erase()。这是非法的。

我猜你应该这样做:

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

但很难说,因为你从来没有解释过你想要完成什么。

【讨论】:

    猜你喜欢
    • 2020-02-03
    • 1970-01-01
    • 1970-01-01
    • 2014-09-26
    • 2014-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多