2017-02-11 69 views
0

我有一個字符串矢量std::vector<string> list,我試圖找到第N個最高的矢量重複元素。C++查找地圖的第N個最高元素

我收到了一張地圖,其中包括矢量元素和它們的重複數。

std::map<std::string , int> mapa; 
for(int i = 0 ; i<list.size() ; i++) 
    mapa[list[i]]++; 

如何從地圖中找到第N個最高的地圖?

實例載體:

qwe asd qwe asd zxc asd zxc qwe qwe asd sdf asd fsd 

如果N是2,我需要出去放像

asd 5 
qwe 4 
+4

你可能想要con sider ['std :: unordered_map'](http://en.cppreference.com/w/cpp/container/unordered_map),['sort'](http://en.cppreference.com/w/cpp/算法/排序)它的值,並獲得第n個第一個元素? –

+0

@Someprogrammerdude我對映射沒有經驗,請指導我如何將向量的成員添加到unordered_map?和地圖一樣嗎? – ffttyy

+1

我建議您按照參考鏈接。但總之,這個接口幾乎和'std :: map'完全一樣。 –

回答

3

您可以使用std::partial_sort

std::map<std::string, std::size_t> 
compute_frequencies(const std::vector<std::string>& words) 
{ 
    std::map<std::string, std::size_t> res; 
    for(const auto& word : words) { 
     res[word]++; 
    } 
    return res;  
} 

std::vector<std::pair<std::string, std::size_t>> 
as_vector(const std::map<std::string, std::size_t>& m) 
{ 
    return {m.begin(), m.end()}; 
} 

int main() { 
    const std::vector<std::string> words{ 
     "qwe", "asd", "qwe", "asd", "zxc", "asd", 
     "zxc", "qwe", "qwe", "asd", "sdf", "asd", "fsd" 
    }; 
    auto frequencies = as_vector(compute_frequencies(words)); 
    std::partial_sort(frequencies.begin(), frequencies.end(), frequencies.begin() + 2, 
     [](const auto& lhs, const auto& rhs) { 
      return lhs.second > rhs.second;  
     }); 
    for (std::size_t i = 0; i != 2; ++i) { 
     std::cout << frequencies[i].first << " " << frequencies[i].second << std::endl; 
    } 
} 

Demo