2017-02-11 6 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であれば、私はあなたがstd::partial_sortを使用する場合があります

asd 5 
qwe 4 
+4

あなたは可能性があります譲りたい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::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

関連する問題