Dont understand the code properly...

As it appears, I have started to learn C++. I am following a book Programming, Principles and Practice using C++ by Stroustrop.
The following code is an exercise from the book and it deletes repeated words. Line number 17 is doing the actual work. But I don't understand how is it doing it.
I want to understand how is it comparing the current string to the whole vector.

Thanks.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
    vector <string> words;
    string temp;
    while(cin >> temp)
        words.push_back(temp);
        cout << "Numbers of words: " << words.size() << endl;

        sort(words.begin(), words.end());
        for (int i = 0; i < words.size(); i++)
            if(i == 0 || words[i - 1] != words[i])
            cot << words[i] << "\n";
    return 0;
}
Bjarne wrote:
What does the test do? It looks to see if the previous word we printed is different from
the one we are about to print (words[i–1]!=words[i]) and if so, we print
that word; otherwise, we do not. Obviously, we can’t talk about a previous
word when we are about to print the first word (i==0), so we first test for
that and combine those two tests using the || (or) operator:
if (i==0 || words[i–1]!=words[i]) // is this a new word?
This part of the text explains line 17 (coincidently I read this part of the text recently). Is there anything in particular that you are having difficulty with?
I want to understand how is it comparing the current string to the whole vector.
It does not. It only compares word by word.

Line number 17 is doing the actual work. But I don't understand how is it doing it.
The point here is that if i==0 is true the second expression words[i–1]!=words[i] is not evaluated.
So only when i != 0 the expression words[i–1]!=words[i] is evaluated.
The reson for this is in case of i==0 i–1 would be invalid.
you just quoted what the book is saying. If I were to understand what the book is explaining, I wouldn't have asked this question.
explain to me the example

when you give these words
a
man
panama
plan
man
it returns
a
man
panama
plan

tell me what is going on behind the scenes. It will make me understand the line number 17.


well...
I get it now. Before it comes to line number 17, the words entered are sorted in ascending order. Then test is applied which checks for the previous words. If its repeated its been deleted.

GOT IT.
Registered users can post here. Sign in or register to post.