2017-05-03 4 views
0

qsortを使用して単語をソートします。配列内で単語が繰り返される回数はどのように数えますか?

これはこれまでのコードですが、どのように繰り返し単語を数えますか?たとえば、リンゴは2回繰り返され、メインは繰り返しません。

int main() 
{ 
    //6 entries with 20 max 
    char strings[6][20] = { "apple", "apple", "strawberries", "bananas", "dairy", "main" }; 

    qsort(strings, 4, 20, (int(*)(const void*, const void*))strcmp); 

    // display the strings in ascending lexicographic order 

    for (int i = 0; i < 6; i++) { 

     cout << strings[i] << "\n"; 
    } 


    return 0; 
} 
+0

あなたは、常に[ 'のstd :: count_if'](HTTPを使用することができます:// en.cppreference.com/w/cpp/algorithm/count)、[このように](http://coliru.stacked-crooked.com/a/17f3f53996e803f8) – cdhowie

+0

「main」の1つの外観が全く繰り返されないように「repeat」を定義している場合、論理的に 'apple'は1回だけ繰り返されます(最初の出現は繰り返しではありません)。 – ShadowRanger

+0

すべての6文字列ではなく、最初の4文字列のみをソートします。 –

答えて

0

より、このような何かを試してみてください:

#include <iostream> 
#include <algorithm> 
#include <string> 

static const int max_strings = 6; 

int main() 
{ 
    //6 entries 
    std::string strings[max_strings] = { "apple", "apple", "strawberries", "bananas", "dairy", "main" }; 

    // sort the strings in ascending order 
    std::sort(strings, &strings[max_strings]); 

    // display the strings and their repeat counts 
    int i = 0; 
    while (i < max_strings) 
    { 
     std::string str = strings[i]; 
     int count = 1; 

     while (++i < max_strings) 
     { 
      if (strings[i] != str) 
       break; 
      ++count; 
     } 

     std::cout << "'" << str << "' appears " << count << " time"; 
     if (count != 1) 
      std::cout << "s"; 
     std::cout << std::endl; 
    } 

    return 0; 
} 

出力:

 
'apple' appears 2 times 
'bananas' appears 1 time 
'dairy' appears 1 time 
'main' appears 1 time 
'strawberries' appears 1 time 

Live Demo

関連する問題