As I study C++ on my own, I tend to come to many barricades. This is one of them. This code was provided for me in the book I am going through. My main question here is this:
What exactly are lines 12 and 13 achieving? I'm not sure I understand what "words[i-1]" and "words[i]" even do.
I do know what the code achieves, I just don't understand the parts that make it move.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include "std_lib_facilities.h"
int main()
{
vector<string>words;
string temp;
while(cin>>temp);
words.push_back(temp);
cout<<"Number of words: "<<words.size()<<endl;
for (int i = 0; i<words.size(); ++i)
if (i==0||words[i-1]!=words[i]) // is this a new word?
cout<<words[i]<<"\n";
}
words[i] is the current word (word number i) words[i-1] is the previous word (word number i-1)
if the current word is not the same as the previous word (words[i-1]!=words[i]), print the current word (cout<<words[i])
since when you're looking at the first word (word number zero), there is no previous word, it has to test for that first, with if(i==0, so the whole if says "if we're looking at the very first word, OR if the current word is not the same as the previous word..."