2015-02-07 51 views
0

這是一條線的形式我輸入文件:值排序C++有很多值的地圖數據結構的關鍵

人口|城市|州| ListOfHighways ==>

6|Oklahoma City|Oklahoma|I-35;I-44;I-40 6|Boston|Massachusetts|I-90;I-93 8|Columbus|Ohio|I-70;I-71

我需要創建一個輸出文件與此以下格式:

Population (newline) City, State Interstates: Comma-separated list of interstates, sorted by interstate number ascending (newline)

==>實施例:

6 

Boston, Massachusetts 
Interstates: I-90, I-93 

Oklahoma City, Oklahoma 
Interstates: I-35, I-40, I-44 

8 

Columbus, Ohio 
Interstates: I-70, I-71 

在這裏,具有相同人口的國家應該組合在一起,他們必須先按州和縣再按字母順序排序。我能夠得到正確的格式,但我無法確定使用哪種數據結構來排序州和城市。我現在有map<int, vector<string> >。關鍵是人口,其餘的是向量。歡迎任何建議。

+1

你可以證明你到目前爲止? – 2015-02-07 05:35:55

+0

有很多方法。一個可能的方向:使用一個結構來保存你的'city','state'和'interstates';使用'map >'並且在載入所有數據後,使用'std :: sort(begin,end,sort_function)對每個'vector'進行排序' – tofi9 2015-02-07 05:38:55

+0

@taoufik感謝您的建議!有效。我能夠使用函數對我的矢量進行排序。 – 2015-02-07 15:19:22

回答

0

我完全不會使用地圖。你應該找出你實際需要的數據的每個元素的信息,並創建你需要的任何數據類型來支持它。例如。

struct State 
{ 
    unsigned int Population; 

    std::vector<std::string> Cities; 

    std::vector<unsigned int> Highways; 
}; 

然後可以分析你的數據,並創建一個std::vector<State>。使用std :: sort適當地對向量和數據進行排序(您可以使用lambdas,或者根據需要創建比較函數或函子)。

+0

是的。這只是我在這裏發佈的程序的一部分。我不得不使用地圖。我能夠通過使用狀態的Struct來解決問題,並使用std :: sort和functor根據國家名稱和城市名稱對它們進行排序。感謝您的建議! – 2015-02-07 15:21:15