c++11 - 设置矩阵零
问题描述
“我正在尝试编写算法,在 A[i][j]=0 的情况下将第 j 行设置为零。”
“我尝试通过打印矩阵 A 的元素而第三个 for 循环
正在将零分配给矩阵的第 j 列以及在整个函数完成之后。令人惊讶的是,在第一种情况下
,第一列的所有元素都为零,但在第二如果列的最后一个元素是 1。""
#include <iostream>
#include<string>
#include<vector>
using namespace std;
/*FUNCTION TO FIND ZEROS AND ASSIGN ith AND jth row AND columns zero
*/
void setZeroes(vector<vector<int> > &A) {
string a,b;/* string a is created to store indexes of rows whose
elemnts are to be converted to zero if atleast one element in the
row is occupied by zero and similarly b is for columns*/
/*for loop to find the indexes of zero elements*/
for(int i=0;i<A.size();i++){
for(int j=0;j<A[0].size();j++){
if(A[i][j]==0){
/*append function stores the indexes in strings*/
a.append(to_string(i));b.append(to_string(j));}
}
}
/*for loop to assign zeros to the elements of ith row*/
for(int i=0;i<a.length();i++){
int j=atoi(&a[i]),k=0;
while(k<A[j].size()){
A[j][k]=0;
k++;}
}
/*for loop to assign zeros to the elements of jth column*/
for(int i=0;i<b.length();i++){
int j=atoi(&b[i]),k=0;
while(k<A.size()){
A[k][j]=0; //every element in A is assigned zero at this point
k++;
}
}
}
//driver function
int main()
{
vector<vector<int>>A={{0,0},{1,1}};
//invoking the setZeroes function
setZeroes(A); for(int i=0;i<A.size();i++){
for(int j=0;j<A[0].size();j++){
cout<<A[i][j]<<" ";// (error)Here A[1][0] is printed as 1
}
cout<<endl;
}
return 0;
}
Input:[
[0, 0]
[1, 1]
]
Expected:[
[0, 0]
[0, 0]
]
Actual:
[
[0, 0]
[1, 0]
]
解决方案
这个atoi(&a[i])
和那个atoi(&b[i])
是错误的。
您假设a
并将b
索引保持在 range 内<0,9>
。因此,要访问它们,您可以减去 48(0 字符的 ascii 代码):
int j = a[i] - 48; // the same with b[i]
或者您可以创建一个字符的字符串,然后atoi
将其转换为整数:
int j = atoi( string(1,a[i]).c_str() ); // this ctor takes one char and creates string
通过这样做atoi(&a[i])
,您正在创建从字符串末尾开始的整数值i-item
- 这不是您想要的。
如果索引可以有两位或更多位,则需要使用一些不同的容器来存储它们,例如字符串向量。
推荐阅读
- arrays - Numpy 抱怨数组模棱两可:ValueError: The truth value
- r - 使用R查找向量中数字的频率
- reactjs - 反应渲染 { [key: string]: object }
- javascript - 日期编辑:从月份中删除零前缀
- javascript - 如何以角度从数组中的数组中删除未定义/空值
- selenium-webdriver - 使用 autoIt 和 selenium 拖放本地文件
- c# - C# LINQ 排列多列值并重新分配到特定列
- c# - 左连接具有某些参数的两个数据表
- r - 汇总 data.table 中名称具有特定模式的列
- qb64 - “火”在击中右边缘后返回 (X 0)