在2-D向量的每列中查找最大值

时间:2017-06-16 16:11:09

标签: c++ max 2d-vector

我创建了一个名为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();
    }
}

1 个答案:

答案 0 :(得分: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的最大元素(刚推入的元素),并将其保存到{{1} }。

我不认为你的代码符合你的想法。你可能想要:

max[j]
相关问题