c++ - 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;
}
解决方案
这是失败所在的行:
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);
....
推荐阅读
- c# - EntityFrameworkCore.SqlServer:无法使用自定义模型类映射数据库表
- vb.net - 当我在代码中没有发现任何错误时,Windows 服务启动然后停止
- javascript - 在从远程设备访问的角度应用程序调用的节点 api 上获取 ERR_CONNECTION_REFUSED
- apache-kafka - 关于 kafka 连接失败的 kafka-streams 警报
- react-native - React-Native:如何绘制具有随机边数的形状(边数将是用户输入值)?
- node.js - 如何在views文件夹中的nestjs应用程序中的hbs模板引擎中设置html模板
- python - 小应用程序在 virtualenv 中的桌面上运行,但在 Heroku 上间歇性失败
- ios - Objective C中的单元测试类参考问题
- javascript - 如何在函数中调用函数?
- ruby-on-rails - 如何使用符号使用比较运算符进行查询