首页 > 解决方案 > C++ Array of Array Products :exited,segmentation fault

问题描述

我是cpp领域的新手。下面是我的cpp代码。当我使用在线c++编译器时,为什么会出现exited、segmentation fault,以及我的代码有什么问题。多谢你们。

问题描述:给定一个整数数组 arr,你被要求为每个索引 i 计算除该索引处的整数之外的所有整数的乘积(即除了 arr[i])。实现一个函数 arrayOfArrayProducts,它接受一个整数数组并返回一个产品数组。在不使用除法的情况下求解并分析解决方案的时间和空间复杂性。

#include <iostream>
#include <vector>

using namespace std;

vector<long> arrayOfArrayProducts(const vector<int>& arr) 
{
  vector<long> res = {};
  int n = arr.size();
  // handles edge cases as well
  if(n==0 || n==1){
    return res;
  }
  

  int product;
  // your code goes here
  for(int i=0; i<n; i++){
    product = 1;
    for(int j=0; j<n; j++){
      if(i!=j){
        product = arr[j]*product;
      }
    res[i]=product;
    }  
  }

  return res;
}

int main() {
  // vector initiallize
  //vector<int> arr{8, 10, 2};
  const vector<int> arr;

  int n = arr.size();

  
  vector<long> ans(n,0);
  ans = arrayOfArrayProducts(arr);
  for(int i=0; i<n; i++){
    cout<< ans[i] <<' ';
  }
  return 0;
}

标签: c++arraysvector

解决方案


这是失败所在的行:

res[i] = product;

原因是你这样声明 res :

vector<long> res = {};

所以你试图访问long位于i空向量的“单元格”的元素......这在 C++ 中是不允许的,结果是未定义的行为

修理它:

与 main 函数中的方法相同

std::vector<long> arrayOfArrayProducts(const std::vector<int>& arr)
{ 
     int n = arr.size(); 
     std::vector<long> res(n, 0);
     ....

推荐阅读