如何在多维矢量中仅添加特定元素并将内容打印到屏幕

How do I add only specific elements in a multidimensional vector and print content to screen

本文关键字:元素 屏幕 打印 添加      更新时间:2023-10-16

我正在研究matrixElementsSum一个关于codefights的任务,更多的代码对我来说似乎没问题,但我在Visual Studio中遇到了下标错误,Codefights编译器遇到了问题。我不知道我错在哪里。我可以得到一些帮助吗

问题是这样的:

成名后,CodeBots决定搬到新大楼住在一起。建筑物由房间的矩形矩阵表示,每个单元格包含一个整数 - 房间的价格。有些房间是免费的(它们的成本是0(,但这可能是因为它们闹鬼,所以所有的机器人都害怕它们。这就是为什么任何空闲房间或位于同一列中空闲房间下方的任何房间都不适合机器人的原因。

帮助机器人计算适合他们的所有房间的总价。

matrix = [[0, 1, 1, 2], 
[0, 5, 0, 0], 
[2, 0, 3, 3]]

输出应为 矩阵元素总和(矩阵( = 9。

以下是标有"x"的不合适房间的房间矩阵:

[[x, 1, 1, 2], 
[x, 5, x, x], 
[x, x, x, x]]

因此,答案是 1 + 5 + 1 + 2 = 9。

我的解决方案是创建一个新矩阵并仅包含我想要的元素输出新创建的矩阵(向量(,然后对所有元素求和并返回总数。

int matrixElementsSum(std::vector<std::vector<int> > matrix) {
std::vector<std::vector<int> > notHaunted;
std::vector<int> room;
for (unsigned int i = 0; i < matrix.size(); i++) {
for (unsigned int  j = 0; j < matrix[i].size(); j++) {
//cout << matrix[i][j];
if (matrix[i][j] == 0) {
cout << " oooo its a haunted room... Lets see if there are more "
<< endl;
}
else {
room.push_back(j);
notHaunted.push_back(room);
}
cout << notHaunted[i][j];
}
cout << endl;
}
int total = 0;
for (unsigned int i = 0; i < notHaunted.size(); i++) {
for (unsigned int  j = 0; j < notHaunted[i].size(); j++)
total += notHaunted[i][j];
}
return total;
}
....
else
{
room.push_back(j);
notHaunted.push_back(room);
}
cout << notHaunted[i][j]; //accessing out of bounds
}

考虑i=0j=0,你的代码进入if部分,所以在打印notHaunted[i][j]时,notHaunted实际上是空的。所以你正在越界访问。 此外,您没有处理您提到的鬼屋下方的房间也闹鬼的部分。

一个简单的方法是首先将所有鬼屋标记为0.然后对整个数组求和。