2012-03-11 6 views
0

나는이 질문을 봤는데 내 코드와 함께 일한 대답을 찾을 수 없었다 그래서 나는이 단어의 빈도를 얻으려고이 문제를 썼다. 나는 잘못된 숫자를 얻고있다. 내 생각에 우연이라고 생각되는 형태를 벗어난 단어들의 출현. 또한 나는 단어가 이미 벡터에 입력되어 있는지 확인하여 동일한 단어를 두 번 계산하지 않습니다.벡터에서 단어 주파수 얻기 C++

fileSize = textFile.size(); 
vector<wordFrequency> words (fileSize); 
int index = 0; 
for(int i = 0; i <= fileSize - 1; i++) 
{ 
    for(int j = 0; j < fileSize - 1; j++) 
    { 
     if(string::npos != textFile[i].find(textFile[j]) && words[i].Word != textFile[j]) 
     { 
      words[j].Word = textFile[i]; 
      words[j].Times = index++; 
     } 
    } 
    index = 0; 
} 

어떤 도움을 주시면 감사하겠습니다.

+0

예상보다 발생 횟수가 더 많습니까? 그리고 당신의 프로그램에서 textfile의 find 멤버 함수는 무엇을합니까 ??? – bhuwansahni

+0

@bhuwansahni 네, 맞습니다. find는 일치하는 문자열을 찾는 벡터 함수입니다. – bobthemac

+0

그리고 실패와 성공에 대한 보상을 찾는 것은 무엇입니까 ?? – bhuwansahni

답변

1

TEXTFILE 벡터에 발생 없음을 찾는 ..

struct wordFreq{ 
    string word; 
    int count; 
    wordFreq(string str, int c):word(str),count(c){} 
    }; 
vector<wordFreq> words; 

int ffind(vector<wordFreq>::iterator i, vector<wordFreq>::iterator j, string s) 
{ 
    for(;i<j;i++){ 
     if((*i).word == s) 
      return 1; 
    } 
    return 0; 
} 

코드를이 코드를 시도하는 것은 그 다음입니다 :를 사용

for(int i=0; i< textfile.size();i++){ 
    if(ffind(words.begin(),words.end(),textfile[i])) // Check whether word already checked for, if so move to the next one, i.e. avoid repetitions 
     continue; 
    words.push_back(wordFreq(textfile[i],1));   // Add the word to vector as it was not checked before and set its count to 1 
    for(int j = i+1;j<textfile.size();j++){   // find possible duplicates of textfile[i] 
     if(file[j] == (*(words.end()-1)).word) 
      (*(words.end()-1)).count++; 
    } 
} 
+0

약간의 조정이 필요했지만 지금은 도움을 주셔서 감사합니다. – bobthemac

+1

아야 ... 이것은 어색합니다! 'map' 또는'unordered_map' 클래스를 사용하는 것이 훨씬 간단합니다! –

+0

지도를 사용하는 것이 훨씬 좋을 수도 있지만 사용하지 않으려는 경우에는 ... – bhuwansahni

2

대신 std::map<std::string,int>을 사용해보십시오. 지도 클래스는 중복되지 않도록 처리합니다. 당신이지도 컨테이너를 사용하지 않는 대신하는 경우

2

연결 컨테이너 :

typedef std::unordered_map<std::string, unsigned> WordFrequencies; 

WordFrequencies count(std::vector<std::string> const& words) { 
    WordFrequencies wf; 
    for (std::string const& word: words) { 
    wf[word] += 1; 
    } 
    return wf; 
} 

더 간단 해지기가 어렵습니다.

참고 : 세계를 사전 순으로 정렬하려면 unordered_mapmap으로 대체하고 대/소문자를 구분하지 않고 사용자 지정 비교 연산을 작성하여 대/소문자를 구분할 수 있습니다.