2017-05-03 1 views
0

프로그램은 qsort를 사용하여 단어를 분류합니다.배열에서 단어가 반복되는 횟수는 어떻게 계산합니까?

이것은 지금까지 가지고있는 코드입니다. 반복되는 단어를 어떻게 계산합니까? 예를 들어, apple은 두 번 반복되지만 main은 전혀 반복하지 않습니다.

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

당신은 항상 ['표준 : count_if'] (HTTP를 사용할 수 있습니다 : // en.cppreference.com/w/cpp/algorithm/count), [this like] (http://coliru.stacked-crooked.com/a/17f3f53996e803f8). – cdhowie

+0

"main"의 한 모양이 반복되는 것으로 간주하지 않도록 "repeat"를 정의하는 경우 논리적으로 'apple'은 한 번만 반복됩니다 (첫 번째 항목은 반복이 아닙니다). – 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

관련 문제