我希望我的数组即使在sort()完成后也能保持基于 1 的索引。我下面的代码在最后一个索引处给了我一个垃圾值,i = n因为循环应该
for(int i = 0; i < n; i++)在排序完成后打印代码时进行。
有没有办法使用std::sort()并仍然保持基于 1 的索引?
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
Run Code Online (Sandbox Code Playgroud)