ポイント間の距離のマトリックスを作成するプログラムを持っています(私のテストファイルでは、3D空間に〜8000ポイントあります)。だから私は(約)8000x8000の行列が欲しいですが、私は倍数(または浮動小数点数)の配列を使用して構築しようとすると、私はいつも 'セグメンテーションフォールト(コアダンプ)'エラーが発生します。なぜどんなアイデア?私は16GBのRAMを持っているので、8000 * 8000 * 8はおよそ0.5GBなので、これは実行可能でなければなりません。また、(以下のコードでコメントアウト)、ベクトルのベクトルとして行列を構築できますが、これは遅いです(約30秒かかります)。それが起こると、私は1.5未満の距離を記録すればよいので、行列は非常に疎です。より良い実装方法があるのは間違いありませんが、これはうまくいかないと私に迷惑をかけています。どんなアドバイスもありがとうございました!C++ 2d arrayはセグメンテーションフォールト(コアダンプ)
//Get distance matrix from .dms file
#include <iostream>
#include <stdlib.h>
#include <fstream>
#include <string>
#include <cmath>
#include <vector>
using namespace std;
double dist(vector<double> a, vector<double> b) {
if (a.size() != b.size()) return -1;
else
{
double dist = 0;
for (int i = 0; i < a.size(); i++) dist += pow(a[i] - b[i], 2);
return dist;
}
}
int main() {
ifstream infile;
ofstream outfile;
vector<vector<double> > points;
string line;
infile.open("1dwr.dms");
outfile.open("1dwr.mat");
while (getline(infile,line))
{
if ((line.at(line.length() - 1)) != 'A')
{
double x[3] = {atof((line.substr(13,8)).c_str()), atof((line.substr(21,9)).c_str()), atof((line.substr(30,9)).c_str())};
vector<double> point;
for (int i=0; i<3; i++)
{
point.push_back(x[i]);
}
points.push_back (point);
}
}
infile.close();
int len = points.size();
double dist_matrix[len][len];
for (int i=0; i<len; i++)
{
for(int j=i; j<len; j++)
{
double d = dist(points[i], points[j]);
if(d < 2.25)
{
dist_matrix[i][j] = sqrt(d);
dist_matrix[j][i] = sqrt(d);
}
}
}
// vector<vector<double> > dist_matrix;
// for (int i=0; i<len; i++)
// {
// vector< double> row;
// for (int j=0; j<len; j++)
// {
// double d = dist(points[i], points[j]);
// if (d < 2.25) row.push_back (sqrt(d));
// else row.push_back (0);
// }
// dist_matrix.push_back (row);
// }
outfile.close();
return 0;
}
デバッガ。スタックオーバーフローを尋ねる前に、コードを一行ずつ進める必要があります。詳しいヘルプは、[小さなプログラムをデバッグする方法(Eric Lippert)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)を参照してください。少なくとも、問題を再現する[最小、完全、および検証可能](http://stackoverflow.com/help/mcve)の例と、デバッガでの観察結果を含めるように質問を編集する必要があります。 –
ありがとうございます。失敗するステップは変数 'double dist_matrix [len] [len]'を宣言しており、変数 'len'が大きすぎるため失敗します。 – user3552101
おそらくスタックオーバーフロー! –