2010-07-27 75 views
1

我想交换两个标准::名单< dontCare项*> ::在Visual 2005化std :: swap返回0xBAADF00D

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

的调剂工作,但迭代当我离开的,如果()范围,it1指向0xbaadfood。 It2是好的,但我尝试了几个变种,包括swap_iter和一个手工交换。

任何帮助表示赞赏:)

编辑

好了,羞时间。

交换it1是if范围内的局部变量。 F ** king cut'n pasting。

F ** king cut'n pasting。对不起,浪费你的时间:/

+6

不要吃它。它会给你火箭筒。 – 2010-07-27 17:11:38

+8

我认为我们需要多一点的代码...... – 2010-07-27 17:22:36

+1

你真的交换了在if范围之外定义的迭代器吗?还是你用在if中定义的一些迭代器交换?容器是否在'if'中定义? – 2010-07-27 17:38:29

回答

3

你在省略if的代码吗?您的if检查中最有可能是其他内容,但交换后实际上使迭代器无效(也许是擦除)。

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 

我。

如果它为您做了其他事情,您的编译器或标准库都会中断。

如果它对你也一样,那么这个错误是你的代码和我的代码之间的差异。我们无法知道,因为我们不知道您的代码。

0

一个WAG,但也许交换是构建新的对象和复制它们(和复制是无效的,因为它使用默认的构造函数)?

+0

请原谅我法语,但那是BS。复制使用拷贝构造函数(并且为支持拷贝构造的所有类型定义了'std :: swap()')。 – sbi 2010-07-27 21:53:56