2012-03-08 37 views
1

我想獲得存儲在向量中的單詞的頻率。我已經無數次地搜索了我的問題,而不是去做一些對我有用的東西。我找到一個網站,有人說使用unique命令來計算單詞的頻率,但我找不到任何這樣做的例子。我可以使用C++中的獨特命令來獲取頻率

+0

您正在使用哪一本C++書? – 2012-03-08 11:28:12

+0

[好的時機](http://stackoverflow.com/questions/9616929/convert-array-to-new-array) – 2012-03-08 11:28:36

+0

我不使用一本書,我在這個網站上說[鏈接](http:// compgroups .net/comp.soft-sys.matlab /計數 - 向量中的每個數字的出現次數) – bobthemac 2012-03-08 11:29:37

回答

6

使用map <string, unsigned>創建一個histogram

using std::string; 
using std::map; 
using std::vector; 

typedef map<string, unsigned> counts_t; 

// Create the histogram 
counts_t histogram; 
for (vector<string>::const_iterator i = vec.begin(); i != vec.end(); ++i) 
    ++histogram[*i]; 

// ... and display it. 
for (counts_t::const_iterator i = histogram.begin(); i != histogram.end(); ++i) { 
    double freq = static_cast<double>(i->second)/vec.size(); 
    std::cout << i->first << ": " << freq << "\n"; 
} 
+1

頻率應該是std :: cout << i->第一個<< ": " << i-> second/vec.size()<<「\ n」; – CapelliC 2012-03-08 11:36:59

+0

@chac:這是OP要求的,但。 – 2012-03-08 11:38:34

+0

@chac呃......你當然是對的。我誤解了這個問題。 – 2012-03-08 11:45:09

1

不使用唯一的,但對於單詞統計它是很難被擊敗及其衍生物的trie或任何,無論是在內存使用&方面速度。

相關問題