1

我正在尝试在 Visual 2005 下交换两个 std::list< dontcare* >::iterators。

Iter it1 = ... ,it2 = ...; // it1 and it2 are ok, not end() or such
if(...){
    std::swap(it1,it2);
}

交换有效,但是当我离开 if() 范围时,it1 指向 0xbaadfood。It2 还可以。我尝试了几种变体,包括 swap_iter 和手工交换。

任何帮助表示赞赏:)

编辑

好吧,太丢脸了。

交换的 it1 是 if 范围内的局部变量。

F**king 剪切粘贴。很抱歉浪费您的时间:/

4

3 回答 3

4

下面这个程序

#include <iostream>
#include <vector>
#include <algorithm>

int main(){
    std::vector<int> v;
    for(std::vector<int>::size_type idx=0; idx<10; ++idx)
        v.push_back(static_cast<int>(idx));

    std::vector<int>::iterator it1 = v.begin();
    std::vector<int>::iterator it2 = v.begin() + v.size()/2;

    std::cout << static_cast<void*>(&*it1) << ':'  << *it1
              << ' ' << static_cast<void*>(&*it2) << ':'  << *it2 << '\n';
    std::swap(it1,it2);
    std::cout << static_cast<void*>(&*it1) << ':'  << *it1
               << ' ' << static_cast<void*>(&*it2) << ':'  << *it2 << '\n';

    return 0;
}

编译、运行,并按预期打印

00032A28:0 00032A3C:5
00032A3C:5 00032A28:0

为了我。

如果它为您做了其他事情,那么您的编译器或标准库都已损坏。

如果它对您也一样,那么错误就在您的代码和我的代码之间的差异中。在哪里,我们不知道,因为我们不知道你的代码。

于 2010-07-27T18:01:05.290 回答
3

您是否在 ? 中省略了代码if?很可能是您if检查中的其他内容,但在交换之后实际上使迭代器无效(可能是擦除)。

于 2010-07-27T17:11:27.687 回答
0

WAG 但可能是交换正在构造新对象并复制它们(并且副本无效,因为它使用默认构造函数)?

于 2010-07-27T18:19:17.170 回答