2013-11-03 51 views
0

所以我有一個圖是這樣的:C++:打印輸出映射值

map<long, MusicEntry> Music_Map; 

MusicEntry包含(名稱,藝術家,大小,並添加日期)

我的問題是如何能打印字符串,我如何打印出地圖中的所有數據?我試圖做...

for(auto it = Music_Map.cbegin(); it!= Music_Map.cend(); ++it) 
    cout << it-> first << ", " << it-> second << "\n"; 

我認爲這個問題正在發生,它不能編譯和讀取第二又名MusicEntry ..

回答

2

您需要提供std::ostream operator<< (std::ostream&, const MusicEntyr&),這樣就可以做這樣的事情:

MusicEntry m; 
std::cout << m << std::endl; 

有了到位,你可以打印地圖的second領域。這裏有一個簡單的例子:

struct MusicEntry 
{ 
    std::string artist; 
    std::string name; 
}; 

std::ostream& operator<<(std::ostream& o, const MusicEntry& m) 
{ 
    return o << m.artist << ", " << m.name; 
} 
2

你的代碼是好的,但你需要實現

std::ostream& operator<<(ostream& os, const MusicEntry& e) 
{ 
    return os << "(" << e.name << ", " << ... << ")"; 
} 

,你可能需要在MusicEntry申報friend上面的訪問私有(或保護的MusicEntry)數據:

class MusicEntry 
{ 
    // ... 

    friend std::ostream& operator<<(ostream& os, const MusicEntry& e); 
}; 

這,當然不是,如果數據是公開的,或者如果你使用公共的getter需要。您可以在operator overloading FAQ找到更多信息。