Is there a way to use std::sort() and still maintain a 1 based indexing?

Viewed 102

I want my array to maintain a 1 based indexing even after the sort() is completed. My code below gives me a garbage value at the last index when i = n because the loop should have been for(int i = 0; i < n; i++) while printing the code after the sort is completed.

Is there a way to use std::sort() and still maintain a 1 based indexing?

int n;
cin >> n; // 6
int a[n+1];
for(int i = 1; i <= n; i++)
    cin >> a[i]; // INPUT ARRAY: 6 4 2 7 2 7
  
sort(a, a+n+1);
for(int i = 1; i <= n; i++)
    cout << a[i] << " "; //  OUTPUT AFTER SORTING: 2 4 6 7 7 6421920
2 Answers

Well yes, only sort starting from index 1.

std::sort(a+1,a+n+1);

Yes, there is a way. Just omit the dummy element when you call sort:

sort(a+1, a+n+1);
Related