2

我在 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++ 文档。(按重试调试应用程序)

4

1 回答 1

1

以下两个错误:

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.

于 2012-12-15T14:56:08.897 回答