You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++ vector版数组右移K位函数无返回结果问题求助

数组右移K位的vector实现问题排查与修复

问题根源分析

你的代码存在两个关键错误:

  • vector未初始化大小:vector<int> subst;创建了一个空vector,直接通过下标subst[j]赋值会触发未定义行为(内存越界),导致程序无法正常返回结果。
  • 元素遍历顺序错误:第一个循环从数组末尾倒序取元素,会把右侧K个元素逆序存入subst,比如原数组的4、5会被存成5、4,不符合预期的{4,5,1,2,3}输出。

修正后的代码

#include<bits/stdc++.h>
using namespace std;

vector<int> rotate_array(vector<int> arr, int n, int key)
{
    int i,j=0;
    // 初始化vector大小为n,避免下标越界
    vector<int> subst(n);

    // 正向遍历右侧K个元素,按顺序存入subst前K位
    for(i = n - key; i < n; i++)
    {
        subst[j] = arr[i];
        j++;
    }

    j=0;
    
    // 将原数组前n-key个元素存入subst的剩余位置
    for(i = key; i < n; i++)
    {
        subst[i] = arr[j];
        j++;
    }

    return subst;
}

int main()
{
    vector<int> arr =  {1, 2, 3, 4, 5};
    // 预期输出:4 5 1 2 3
    int n = arr.size();
    int key = 2;
    vector<int> array = rotate_array(arr, n, key);
    for(int i=0; i<n; i++)
    {
        cout<<array[i]<<" ";
    }
}

额外优化建议

  • 函数参数vector<int> arr可以改为const vector<int>& arr,避免不必要的数组拷贝,提升性能。
  • 处理key大于n的情况(比如key=7,n=5),可以先做key = key % n;,确保key在有效范围内。

内容的提问来源于stack exchange,提问作者Anjali Sharma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 23:54:23