2017-06-16 16 views
0

私はcosmic_ray_eventsという2次元ベクトルを作成しました。それは1234487行と9列を持っています。私はすべての行から各列の最大値を探したい。コードを実行しようとするたびにセグメンテーション違反が発生しています。また、datファイルから値をロードすることによってcosmic_ray_eventsベクトルを作成しました。アドバイスをいただければ幸いです。2次元ベクトルの各列の最大値を求める

vector<vector<double> > cosmic_ray_events(total_cosmic_ray_events, vector<double>(9,0)); 
ifstream cosmic_ray_data("events_comp-h4a_10.00-10000.00PeV_zen37.00.dat", ios::in); 

while(cosmic_ray_data.good())  
{ 
    for(int i = 0; i < 1233487; i++) //1233487 is the number of rows in the dat file 
    { 
     for(int j = 0; j < cosmic_columns; j++) 
     { 
       cosmic_ray_data >> cosmic_ray_events[i][j]; //reading in data for 2-D vector 
     } 
    } 
} 

double max[9]; 
std::vector<double> find_max; 
for(int i = 0; i < 1234487; i++) 
{ 
    for(int j = 0; j < 9; j++) 
    { 
     find_max.push_back(cosmic_ray_events[i][j]); 
     max[j] = *max_element(find_max.begin(), find_max.end()); 
     find_max.clear(); 
    } 
} 

答えて

0

あなたがstd::vectorを使用しているので、あなたは自分を支持を行うと、すべてのルックアップの範囲チェックを行うことができます。これにより、segfaultが防止され、代わりにわかりやすいエラーメッセージが返されます。それを行うと、次のようになります。

vector<vector<double> > cosmic_ray_events(total_cosmic_ray_events, vector<double>(9,0)); 

ifstream cosmic_ray_data("events_comp-h4a_10.00-10000.00PeV_zen37.00.dat", ios::in); 

while(cosmic_ray_data.good()){ 
    for(int i = 0; i < 1233487; i++){ //1233487 is the number of rows in the dat file 
    for(int j = 0; j < cosmic_columns; j++){ 
     cosmic_ray_data >> cosmic_ray_events.at(i).at(j); //reading in data for 2-D vector 
    } 
    } 
} 

double max[9]; 
std::vector<double> find_max; 
for(int i = 0; i < 1234487; i++){ 
    for(int j = 0; j < 9; j++){ 
    find_max.push_back(cosmic_ray_events.at(i).at(j)); 
    max[j] = *max_element(find_max.begin(), find_max.end()); 
    find_max.clear(); 
    } 
} 

また、ループの最後のセットはfind_maxに単一の要素を紹介することに注意し、find_max(要素はあなただけで押し込ん)の最大の要素を見つけ、保存しmax[j]への。

あなたのコードはあなたが思うとは思わないと思います。

std::vector<double> max_vals(9,-std::numeric_limits<double>::infinity()); 
for(int i = 0; i < 1234487; i++){ 
    for(int j = 0; j < 9; j++){ 
    max_vals.at(j) = std::max(max_vals.at(j),cosmic_ray_events.at(i).at(j)); 
    } 
} 
+0

ありがとうございました。私は最後のループのセットが私に、各要素が各列の最大値である9個の要素だけを含むベクトルを与えてしまうと思いました。代わりにfind_maxを2-dベクトルにする必要がありますか? –

+0

@michaelkovacevich:いいえ、私の編集した答えを見てください。 – Richard

関連する問題