2017-04-10 80 views
1

我的目標是檢查向量中的重複項並將它們與其重複計數一起發佈。例如:檢查向量中的重複項並計算它們C++

vector<string> vec{"words", "words", "are", "fun", "fun", "fun"}; 
// words - 2 
// fun - 3 

我已經找到很好的解決方案,但我不知道有沒有打印計數器任何可能的方式:

vector<string> vec{"words", "words", "are", "fun", "fun", "fun"}; 
sort(vec.begin(), vec.end()); 
set<string> uvec(vec.begin(), vec.end()); 
list<string> output; 

set_difference(vec.begin(), vec.end(), 
       uvec.begin(), uvec.end(), 
       back_inserter(output)); 

for (list<string>::iterator i = output.begin(); i != output.end(); ++i) 
    cout << *i << endl; 
+0

你正在使用什麼編譯器(哪一個版本和哪個版本)? – Rerito

回答

3

你可以簡單地保持map計數的單詞數。

vector<string> vec{"words", "words", "are", "fun", "fun", "fun"}; 
map<string, int> words; 
for(const auto& x : vec) ++(words[x]); 

for(const auto& [k, v] : words) 
    if(v > 1) cout << k << " - " << v << "\n"; 

live wandbox example


請注意,我使用的是C++ 17的功能,稱爲「結構化綁定」來解構words的成對[k, v]。如果您沒有C++ 17編譯器,則可以使用const auto& p : words並使用p.firstp.second訪問配對成員。

+0

我忘了我們現在可以在野外看到C++ 17:') –

+0

我在第二個for循環中出現const錯誤。我應該包括任何東西。說「預計表達」 – TeodorKolev

+0

@TeodorKolev:我正在使用稱爲「結構化綁定」的C++ 17功能。如果您沒有C++ 17編譯器,則可以使用'const auto&p:words'並使用'p.first'和'p.second'訪問配對成員。 –

相關問題