2010-07-27 36 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

相關問題