0

我创建了一个名为 cosmic_ray_events 的二维向量。它有 1234487 行和 9 列。我想从所有行中找出每一列的最大值。每当我尝试运行我的代码时,我都会遇到分段错误,我知道为什么。我还通过从 dat 文件中加载值来创建 cosmic_ray_events 向量。任何建议表示赞赏。

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();
    }
}
4

1 回答 1

0

由于您使用的是std::vector,因此您可以帮自己一个忙,并对每次查找进行范围检查。这将防止段错误并改为返回可理解的错误消息。这样做看起来像这样:

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));
  }
}
于 2017-06-16T16:24:09.707 回答