我是新來的地圖,所以有點不確定這樣做的最佳方式。這個任務與使用霍夫曼編碼進行壓縮有關。這裏有我的。上述用字符串中的2個鍵填充地圖。字符和頻率C++
#include <map>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
typedef map<char,int> huffmanMap;
void getFreq(string file, map<char, int> map)
{
map.clear();
for (string::iterator i = file.begin(); i != file.end(); ++i) {
++map[*i];
}
}
是一個方法,我在網上找到,但無法打印任何東西,
int main()
{
map<char, int> huffmanMap;
string fileline;
ifstream myfile;
myfile.open("text.txt",ios::out);
while(!myfile.eof()) {
getline(myfile, fileline); //get the line and put it in the fileline string
}
myfile.close();
我在從一個文本文件中讀取來填充字符串fileline。
for (int i=0; i<fileline.length(); i++) {
char t = fileline[i];
huffmanMap[i]? huffmanMap[i]++ : huffmanMap[i]=1;
}
這裏是我試過用於填充圖的第二種方法,char值是不正確的,符號和smileyfaces ..
getFreq(fileline,huffmanMap);
huffmanMap::iterator position;
for (position = huffmanMap.begin(); position != huffmanMap.end(); position++) {
cout << "key: \"" << position->first << endl;
cout << "value: " << position->second << endl;
}
這是我試圖打印地圖
system("pause");
return 0;
}
當我運行我的getFreq方法時,程序崩潰。我沒有得到任何錯誤。用第二種方法char值是無意義的。注意我沒有同時運行這兩種方法,我只是將它們都包含在內,以顯示我所嘗試的內容。
任何有識之士將不勝感激。謝謝。從寬鬆的初學者;)
我修復了你的absymal格式。在將帖子提交給Stack Overflow之前,請使用「預覽窗格」。 – 2011-03-11 11:42:21
'while(!.eof)'是錯誤的:http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.5。你從哪裏看到這是對的?很多人都這樣做,我想找出原因。 – 2011-03-11 11:43:10
另外,您的調試器對此問題有何評論? – 2011-03-11 11:45:32