在c ++中将变量分配给vector的向量元素时出错

问题描述 投票:-2回答:1
void fun(vector<vector<int >> &vec){
      int l=0, r=0;
        int n = vec.size();
         for(int i=0;i<n;i++){
          for(int j=0;j<vec[i].size()-1;j++){
             if(vec[i][j]==0)
                    l+= vec[i][j+1];
             if(vec[i][j] == 1)
                    r+= vec[i][j+1]; 
           } 
         }
  }
 I have only two column in the matrix eg. [[0,3],[1,9],[0,7]]
 so i can do like that 

 for(int i=0;i<n;i++){
                 if(vec[i][0]==0)
                       l+= vec[i][1];
                 if(vec[i][0] == 1)
                         r+= vec[i][1]; 
             }

但以上行(l + = vec [i] [1]和r + = vec [i] [1]给我错误)但是我能够打印cout<<vec[i][1],但不能存储元素总数:

AddressSanitizer:DEADLYSIGNAL
=================================================================
==32==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000000 (pc 0x000000385fd7 bp 0x7ffe843426f0 sp 0x7ffe84342640 T0)
==32==The signal is caused by a READ memory access.
==32==Hint: address points to the zero page.
    #7 0x7fd0ef11f82f  (/lib/x86_64-linux-gnu/libc.so.6+0x2082f)
AddressSanitizer can not provide additional info.
==32==ABORTING

需要帮助!

c++ stl
1个回答
-1
投票

如果您需要向量具有m✕n个矩阵,则需要这样做。

vector<vector<int >> vec;
vec.resize(m);
for(auto& v:vec)
    v.resize(n);
© www.soinside.com 2019 - 2024. All rights reserved.