Given a vector of integers, iterate through the vector and check whether there are more than one of the same number. In that case, remove them so that only a single index of the vector contains that number. Here are a few examples:
vector<int> arr {1,1,1,1} When arr is printed out the result should be 1. vector<int> arr {1,2,1,2} When arr is printed out the result should be 1,2. vector<int> arr {1,3,2} When arr is printed out the result should be 1,3,2.
I know there are many solutions regarding this, but I want to solve it using my method. The solutions I've looked at use a lot of built-in functions, which I don't want to get too comfortable with as a beginner. I want to practice my problem-solving skills.
This is my code:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> arr {1,1,1,1,2,1,1,1,1,1};
for (int i {}; i < arr.size(); ++i)
{
int counter {};
for (int j {}; j < arr.size(); ++j)
{
if (arr.at(i) == arr.at(j))
{
counter++;
if (counter > 1)
arr.erase(arr.begin()+j);
}
}
}
//Prints out the vector arr
for (auto value : arr)
{
cout << value << endl;
}
return 0;
}
The thing is that it works for the most part, except a few cases which have me confused.
For instance:
vector<int> arr {1,1,1,1,2,1,1,1,1,1}
When arr is printed out the result is 1,2,1 instead of 1,2.
However, in this case:
vector<int> arr {1,1,1,1,2,1,1,1}
When arr is printed out the result is 1,2.
It seems to work in the vast majority of cases, but when a number repeats itself a lot of times in the vector, it seems to not work, and I can't seem to find a reason for this.
I am now asking you to firstly tell me the cause of the problem, and then to give me guidance on how I should tackle this problem using my solution.