I was trying to use auto & in ranged for loop to modify the value. But I was so shocked that it did not work "ALL THE TIME". I attach my original code below. It simply find element 0 in a matrix and set the corresponding row and column to all zeros.
#include<iostream>
#include<vector>
using namespace std;
void zerolify(vector<vector<int>>& m)
{
int row=m.size();
int col=col>0?m[0].size():0;
vector<int> r(row,0);
vector<int> c(col,0);
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
if(m[i][j]==0)
{
r[i]=1;
c[j]=1;
}
}
}
for(int i=0;i<row;i++)
{
if(r[i])
{
//cout<<"row: "<<i<<endl;
for(auto &e : m[i])
{
e=0;
}
//for(int j=0;j<col;j++)
//{
// m[i][j]=0;
//}
}
}
for(int i=0;i<col;i++)
{
if(c[i])
{
for(int j=0;j<row;j++)
{
m[j][i]=0;
}
}
}
}
void printMatrix(vector<vector<int>> m)
{
for(auto i:m)
{
for(auto j:i)
{
cout<<j<<" ";
}
cout<<endl;
}
}
int main(int argn, char** argv)
{
vector<vector<int>> m(5,vector<int>(5));
m[0]={1,2,3,0,4};
m[1]={1,1,3,5,4};
m[2]={1,2,3,0,4};
m[3]={1,2,3,5,4};
m[4]={1,2,3,5,4};
cout<<"Original matrix:"<<endl;
printMatrix(m);
zerolify(m);
cout<<"Zerolify"<<endl;
printMatrix(m);
return 0;
}
I am using Mac OS 10.12.2 with Apple LLVM version 8.0.0 (clang-800.0.42.1) compiler. Here is my results: My command line output
You can see that the first time it did not work leaving the matrix unchanged. The second time it worked. I tried also auto &&, it gave me the same 'uncertain' behavior. But for loop with direct indexing work all the time (commented out in the code). Currently, I could not replicate the problem in any other case, however the logics here is already simple enough.
Could it be compiler problem ? Can anyone run the code and see if the problem can be replicated ?
Aucun commentaire:
Enregistrer un commentaire