In this program, we will share a C++ program to remove consecutive same words. If you are a beginner and want to start learning the C++ programming, then keep your close attention in this tutorial as I am going to share how to remove consecutive same words from a sentence using the C++ program.
Copy the below C++ program and execute it with the help of GCC compiler. At the end of this program, We have shared the output of this program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | #include<bits/stdc++.h> using namespace std; int removeConsecutiveSame(vector <string > v) { int n = v.size(); for (int i=0; i<n-1; ) { if (v[i].compare(v[i+1]) == 0) { // i is not updated v.erase(v.begin()+i); v.erase(v.begin()+i); if (i > 0) i--; n = n-2; } else i++; } return v.size(); } int main() { vector<string> v = { "tom", "jerry", "jerry", "tom"}; cout << removeConsecutiveSame(v); return 0; } |
1 – 3
4 – 3
4 – 5
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.