【问题标题】:Returning vector array from a function从函数返回向量数组
【发布时间】:2022-07-18 00:43:36
【问题描述】:

我实际上是在尝试解决 K 旋转问题,我们必须将元素的键数向右旋转并将它们放在左侧。 我已经使用普通数组而不是向量检查了整个代码,它工作正常,但是当我运行它时,带有向量数组的函数从不返回任何内容。 我检查了所有在线资源,但由于逻辑和语法都是正确的,因此无法确定究竟是什么错误。 请帮忙解决这个问题!

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

vector<int> rotate_array(vector<int> arr, int n, int key)
{
    int i,j=0;
    vector<int> subst;

    for(i=n-1; i>=n-key; i--)
    {
        subst[j] = arr[i];
        j++;
    }

    j=0;
    
    for(i=key; i<n; i++)
    {
        subst[i] = arr[j];
        j++;
    }

    return subst;
}

int main()
{
    vector<int> arr =  {1, 2, 3, 4, 5};
    // output for this should be -- {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]<<" ";
    }
}

【问题讨论】:

    标签: c++ arrays vector


    【解决方案1】:

    函数rotate_array中的向量subst没有元素,所以访问它的“元素”(subst[j]subst[i])是非法的。

    你必须分配元素。例如,您可以使用构造函数来做到这一点:

    vector<int> subst(n); // specify the number of elements to allocate
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-13
      • 2013-07-02
      • 2023-03-09
      • 1970-01-01
      • 2018-09-19
      • 2012-08-31
      相关资源
      最近更新 更多