c++ - Trying count distinct strings, whats going wrong -
whats wrong in approach
#include<algorithm> #include<iomanip> #include<ios> #include<iostream> #include<string> #include<vector> using std::cin;using std::cout; using std::endl; using std::setprecision; using std::string; using std::streamsize; using std::sort; using std::vector; int main(){ string zz; typedef vector<string> vs; vs input,distinct;vector<int> count; cout<<"enter words"; while(cin>>zz){ input.push_back(zz); } if(input.size()==0){ cout<<"enter atleast single word"; return 1; } int i=0,j=0; sort(input.begin(),input.end()); while(i!=input.size()){ int count2=0; for(j=i;j<input.size();j++) { if(input[j]==input[j+1]) { count2++; }else{ break; } } distinct.push_back(input[i]); count.push_back(count2); i+=count2;continue; i++; } for(i=0;i<distinct.size();i++) { cout<<distinct[i]<<"\t time"<<count[i]<<"\n"; } return 0; } i using ubuntu 12.10 gcc4.7
the task 2 count distinct number of given inputs , display it. program ask input , doesnt stop taking input after end of file i.e ctrl+d
the problem not read loop. gets stuck in infinite loop in
while(i!=input.size()){ think end condition, , lines change i:
i+=count2;continue; i++; will i++ ever executed? i ever exactly equal input.size()? if there are repeated words? if there not?
.
.
.
ok, thought it? replaced loop this. comments should explain:
while(i < input.size()) { // store current string distinct.push_back(input[i]); // skip same strings int j = i; while ( j < input.size() // don't go far && input[i] == input[j] ) // , while duplicates ++j; // store count of how many skipped count.push_back(j-i); // move next *non-identical* string i=j; } of course, there nicer ways using standard library algorithms, assume simple educational exercise.
note way round wrote && matters! other way round , try compare last string off end.
Comments
Post a Comment