我正在 Bjarne Stroustrup (C++) 的(翻译成荷兰语的)书中尝试这个例子:
#include <vector>
#include <list>
#include "complex.h"
complex ac[200];
std::vector<complex> vc;
std::list<complex> l;
template<class In, class Out> void Copy(In from, In too_far, Out to) {
while(from != too_far) {
*to = *from;
++to;
++from;
}
}
void g(std::vector<complex>& vc , std::list<complex>& lc) {
Copy(&ac[0], &ac[200], lc.begin()); // generates debug error
Copy(lc.begin(), lc.end(), vc.begin()); // also generates debug error
}
void f() {
ac[0] = complex(10,20);
g(vc, l);
}
int main () {
f();
}
** 编译和链接成功(0 个错误/警告)**
但是在运行时我得到这个错误:
调试断言失败!
程序:exe路径
文件:\program files\ms vs studio 10.0\vc\include\list
行:207
表达式:列表迭代器不可取消引用
有关您的程序如何导致断言失败的信息,请参阅有关断言的 Visual C++ 文档。 (按重试调试应用程序)
最佳答案
以下两种错误:
Copy(&ac[0], &ac[200], lc.begin()); // generates debug error
Copy(lc.begin(), lc.end(), vc.begin()); // also generates debug error
您的 Copy()
函数会覆盖从作为第三个参数提供的迭代器开始的元素。因此,目标范围必须有效且足够大以容纳所有被复制的元素。 lc
和 vc
都不满足这一点,因此您的代码的行为是未定义的。
修复代码的一种方法是使用 std::back_inserter
.
关于c++ - 为什么我得到这个调试断言失败?表达式 : list iterator not dereferenceable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13893237/