给定一个整数向量,遍历该向量并检查是否有多个相同的数字。在这种情况下,请删除它们,以便只有向量的单个索引包含该数字。这里有一些例子:
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.
我知道对此有很多解决方案,但我想用我的方法解决它。我看过的解决方案使用了很多内置函数,作为初学者,我不想太适应。我想锻炼我解决问题的能力。
这是我的代码:
#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;
}
问题是它在大多数情况下都有效,除了一些让我感到困惑的情况。
例如:
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.
但是,在这种情况下:
vector<int> arr {1,1,1,1,2,1,1,1}
When arr is printed out the result is 1,2.
它似乎在绝大多数情况下都有效,但是当一个数字在向量中重复很多次时,它似乎不起作用,我似乎找不到原因。
我现在要求您首先告诉我问题的原因,然后指导我应该如何使用我的解决方案来解决这个问题。