2012-04-03 90 views
-1

崩潰我有一個字符串映射在它的兩個條目: "Chicago"--> ChicagoObj"NewYork"-->NewYorkObj,其中ChicagoObjNewYorkObj是指針的MyClass對象。的std ::地圖適用於Windows 32位,但在64位

以下代碼在32位編譯並運行正常,它在64位編譯,但在打印芝加哥條目後總是在64位崩潰。任何幫助表示讚賞!

typedef std::map<std::string, MyClass*> MyStringMap; 
MyStringMap my_map; 

std::string key1="Chicago"; 
MyClass *ChicagoObj = new MyClass; 
my_map[key1] = ChicagoObj; 

std::string key2="NewYork"; 
MyClass *NewYorkObj = new MyClass; 
my_map[key2] = NewYorkObj ; 

MyStringMap::iterator iObjMap = my_map.begin(); 

while (iObjMap != my_map.end()) 
{ 
    std::string key = iObjMap->first; 

    std::cout<<"name of the key in the map: " << key <<std::endl; 
    iObjMap++; 
} 
+1

我看到「字符串」和「std :: string」的混合使用,我假設一個錯字,否則可能「字符串」根本可能不是一個「std :: string」。 – SirDarius 2012-04-03 16:22:31

+3

即使在這種情況下它看起來無害,你也不應該使用像'std :: string'這樣的對象類型的'C'類型轉換。 – Chad 2012-04-03 16:27:49

+0

這段代碼是否實際編譯?它似乎缺少一些東西,例如什麼是「my_map」? – josephthomas 2012-04-03 16:27:58

回答

0

確定您已經編譯了最新的代碼,並且沒有運行帶有以前的錯誤的程序嗎?我已經在Windows 7 64上的Visual Studio 2010中編譯了代碼,並且沒有任何問題。

雖然代碼中有編譯錯誤,但是std::out應該是std::cout。除此之外,甚至沒有來自/ Wall的警告。

+0

「甚至沒有來自/ Wall的警告。」這不可能是真的。標準庫頭文件(比如'')不會乾淨地用/ Wall編譯。你的意思是/ W4? – 2012-04-03 17:17:22

+0

我是指他的代碼中的/ Wall,而不是其他包含的。 – josephthomas 2012-04-03 17:23:41

0

既然你顯然不會發佈一個完整的,可編譯的代碼來說明問題,下面是它如何工作的一個簡短演示:

#include <map> 
#include <iostream> 
#include <string> 
#include <iterator> 

class City { 
    unsigned int population; 
    // probably more stuff here, but this should be enough for now. 
public: 
    City(int pop=0) : population(pop) {} 

    friend std::ostream &operator<<(std::ostream &os, City const &c) { 
     return os << c.population; 
    } 

}; 


std::ostream &operator<<(std::ostream &os, 
         std::pair<std::string, City> const &d) 
{ 
    return os << d.first << ": " << d.second; 
} 

int main() { 
    std::map<std::string, City> cities; 
    typedef std::pair<std::string, City> ct; 

    cities["Chicago"] = City(3456789); 
    cities["New York"] = City(8765432); 

    std::copy(cities.begin(), cities.end(), 
     std::ostream_iterator<ct>(std::cout, "\n")); 

    return 0; 
} 

我編譯和測試,這對64位Windows,它似乎工作得很好。這似乎(至少對我來說)map在64位Windows上可以正常工作。確切地說,你已經完成的工作很難被猜出,但是擴展工作代碼來做你想做的事可能更容易,而不是找出那些無法工作的代碼中損壞的東西。

相關問題