Reputation: 1
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector <int> arr = { -12, 14, 71, 123, 12, -14, 5, 5, -75, 12, -1, 51, 12, 61, -61, -13 };
int n = arr.size();
for (int i = 0; i < n; i++)
{
for (int j=0;j<n;j++)
{
if (arr[j] < arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
else if (arr[j] == arr[j + 1])
{
for (int a = j + 1; a < n; a++)
{
arr[a] = arr[a + 1];
}
}
}
}
for (int i : arr)
{
cout << i << endl;
}
return 0;
}
It works if I use an array but it shown "vector subscript out of range" when I use vector. Could anyone please explain why is it an error there?
Upvotes: 0
Views: 147
Reputation: 191
your vector element size is n. But,you are using index over n incase of arr[j+1] and arr[a+1].
Just put condition checking, i < n-1 , j < n-1 and a < n-1
Here is the updated code:
vector <int> arr = { -12, 14, 71, 123, 12, -14, 5, 5, -75, 12, -1, 51, 12, 61, -61, -13 };
int n = arr.size();
for (int i = 0; i < n-1; i++)
{
for (int j = 0; j < n-1; j++)
{
if ( arr[j] < arr[j + 1] )
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
else if ( arr[j] == arr[j + 1])
{
for (int a = j + 1; a < n - 1; a++)
{
arr[a] = arr[a + 1];
}
}
}
}
for (int i : arr)
{
cout << i << endl;
}
Upvotes: 0
Reputation: 120
Consider the following fragment of your code:
for (int j=0;j<n;j++)
{
if (arr[j] < arr[j + 1])
What will happen on the last loop iteration, when j = n - 1
?
Upvotes: 2
Reputation: 7726
You are trying to access out-of-bound array with this line:
arr[j + 1] AND arr[a + 1]
because it is iterating only till n
. In the last valid iteration, the program tries to obtain the value of j + 1
th and n + 1
th indices respectively whereas the size of the array is n
.
To solve this issue, you need to iterate till n - 1
condition. Just replace those n
contained in the nested two For loops so that it will correctly iterate till the end of the loop.
Upvotes: 0