Okay so I was wondering if there is a way to return a incremented iterator but now increment it. Let me clear this up a little.
So this is what I have written by using indexes instead of iterators.
It counts the amount of times a duplicated word comes beside itself
Such as
input: how now now now brown cow cow
out: now occurred 3 times.
// Keyboard keys \ |
#include <iostream>
#include <string>
#include <vector>
using std::cout; using std::endl; using std::cin;
using std::string; using std::vector;
int main()
{
string input; // for getting input
vector<string> words; // for storing our input
cout << "This program will find duplicated words that are beside each other.\nType words, once finished press CTRL+Z/D (Windows/Unix) " << endl;
while (cin >> input) { // get input until we hit end-of-file
words.push_back(input); // store that input in a vector called word
}
unsigned counter = 0, finalCnt = 0;
string word;
for (unsigned index = 0; index != words.size() - 1; ++index) {
if (words[index] == words[index + 1]) {
++counter;
if (counter >= finalCnt && counter == 1) {
finalCnt = 2;
word = words[index];
}
elseif (counter >= finalCnt) {
++finalCnt;
word = words[index];
}
} else {
counter = 0;
}
}
if (finalCnt != 1) {
cout << word << " occurred " << finalCnt << " times." << endl;
} else {
cout << "There were no duplicate words" << endl;
}
return 0;
}
// Keyboard keys \ |
#include <iostream>
#include <string>
#include <vector>
using std::cout; using std::endl; using std::cin;
using std::string; using std::vector;
int main()
{
string input; // for getting input
vector<string> words; // for storing our input
cout << "This program will find duplicated words that are beside each other.\nType words, once finished press CTRL+Z/D (Windows/Unix) " << endl;
while (cin >> input) { // get input until we hit end-of-file
words.push_back(input); // store that input in a vector called word
}
unsigned counter = 0, finalCnt = 0;
string word;
for (auto beg = words.cbegin(); beg != words.cend() - 1; ++beg) {
auto secondWord = beg;
++secondWord;
if (*beg == *secondWord) {
++counter;
if (counter >= finalCnt && counter == 1) {
finalCnt = 2;
word = *beg;
}
elseif (counter >= finalCnt) {
++finalCnt;
word = *beg;
}
} else {
counter = 0;
}
}
if (finalCnt != 1) {
cout << word << " occurred " << finalCnt << " times." << endl;
} else {
cout << "There were no duplicate words" << endl;
}
return 0;
}
As you can see I have another iterator declared(secondWord). Is there a way I can do that without secondWord.
like this wont work if (*beg == *++beg)
as its incrementing beg. I would like to dereference the next word but not advance beg.
Thank you guys, I tried *beg + 1 without () and got an error. Thanks that did the trick
What exactly does std::advance do. Like does it make a temp iterator?