我正在开发一个程序,该程序应该对整数向量进行排序,然后传递给递归函数以通过元素检查它的邻居来删除任何重复项,如果它们相同则将其删除。这是我的代码:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void checkNum(vector<int> &v, int n)
{
int i = n;
if (v[i] == '\0')
{
cout << "No duplicates found." << endl;
}
if (v[i]==v[i+1])
{
v.erase(v.begin()+i);
/*return 1 + */checkNum(v, n);
}
else
{
n++;
/*return 0 + */checkNum(v, n);
}
int k;
cout << "Sorted values, no duplicates: " << endl;
for (k=0; k< v.size(); k++)
cout << v[k] << " ";
//return 0;
}
int main()
{
vector<int> numbers;
cout << "Please enter numbers, 0 to quit: " << endl;
bool more = true;
while (more)
{
int num;
cin >> num;
if (num == 0)
more = false;
else
numbers.push_back(num);
}
sort(numbers.begin(),numbers.end());
cout << "The sorted values are: " << endl;
int i;
for (i = 0; i < numbers.size(); i++)
cout << numbers[i] << " ";
checkNum(numbers, 0);
system("pause");
return 0;
}
我的问题是,当它运行时,输入值后出现以下错误:
Debug Assertion Failed!
Program: C:\Windows\system32\MSVCP110D.dll File: d:\program files (x86)\microsoft visual studio 11.0\vc\include\vector Line: 1140
Expression: vector subscript out of range
它在工作时也会打印多次,但我对此并不十分担心。错误在哪里?有人可以帮帮我吗?
更新:
这是我目前正在运行的代码:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int checkNum(vector<int> &v, int n)
{
int i = n;
if (i == v.size())
{
cout << "No duplicates found." << endl;
return 0;
}
if (v[i]==v[i+1])
{
v.erase(v.begin()+i);
return checkNum(v, n);
}
else
{
n++;
return checkNum(v, n);
}
int k;
cout << "Sorted values, no duplicates: " << endl;
for (k=0; k< v.size(); k++)
cout << v[k] << " " << endl;
return 0;
}
int main()
{
vector<int> numbers;
cout << "Please enter numbers, 0 to quit: " << endl;
bool more = true;
while (more)
{
int num;
cin >> num;
if (num == 0)
more = false;
else
numbers.push_back(num);
}
sort(numbers.begin(),numbers.end());
cout << "The sorted values are: " << endl;
int i;
for (i = 0; i < numbers.size(); i++)
cout << numbers[i] << " ";
checkNum(numbers, 0);
system("pause");
return 0;
}
我用调试器运行,一切都很好,删除重复项好像没什么大不了的,直到 n/i 的大小达到列表的大小。然后我收到上面列出的错误消息。我该如何解决?