Q:

vector element compare c++

This program takes a word from text and puts it in a vector; after this it compares every element with the next one.
So I'm trying to compare element of a vector like this:
sort(words.begin(), words.end());
int cc = 1;
int compte = 1;
int i;
//browse the vector
for (i = 0; i <= words.size(); i++) {     // comparison
    if (words[i] == words[cc]) { 
        compte = compte + 1; 
    }

    else {     // displaying the word with comparison
        cout << words[i] << " Repeated :  " << compte; printf("\n");
        compte = 1; cc = i;
    }
}

My problem in the bounds: i+1 may exceed the vector borders. How to I handle this case?

A:

You need to pay more attention on the initial conditions and bounds when you do iteration and comparing at the same time. It is usually a good idea to execute your code using pen and paper at first.
sort(words.begin(), words.end()); // make sure !words.empty()
int cc = 0; // index of the word we need to compare.
int compte = 1; // counting of the number of occurrence.
for( size_t i = 1; i < words.size(); ++i ){
    // since you already count the first word, now we are at i=1
    if( words[i] == words[cc] ){
        compte += 1;
    }else{
        // words[i] is going to be different from words[cc].
        cout << words[cc] << " Repeated :  " << compte << '\n';
        compte = 1;
        cc = i;
    }
}
 // to output the last word with its repeat 
cout << words[cc] << " Repeated :  " << compte << '\n';

Just for some additional information.
There are better ways to count the number of word appearances.
For example, one can use unordered_map<string,int>.
Hope this help.

