如何在多维矢量中仅添加特定元素并将内容打印到屏幕
How do I add only specific elements in a multidimensional vector and print content to screen
我正在研究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=0
和j=0
,你的代码进入if
部分,所以在打印notHaunted[i][j]
时,notHaunted
实际上是空的。所以你正在越界访问。 此外,您没有处理您提到的鬼屋下方的房间也闹鬼的部分。
一个简单的方法是首先将所有鬼屋标记为0
.然后对整个数组求和。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用strcpy将char数组的元素复制到另一个数组
- 使用不带参数的函数访问结构元素
- 给定n个元素的m个集合.在C++中找到出现在最大集合数中的元素
- C++如何通过用户输入删除列表元素
- lower_bound()返回最后一个元素
- 基于多个条件处理地图中的所有元素
- 调整大小后指向元素值的指针unordered_map有效?
- 使用std::transform将一个范围的元素添加到另一个范围中
- 使用函数"remove"删除重复元素
- 具有最大子序列大小的序列,每个元素都相同
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 如何将元素添加到数组的线程安全函数?
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- 我想访问std::unique_ptr中的一个特定元素
- 如何通过 getter 函数删除矢量的元素?
- 如何在多维矢量中仅添加特定元素并将内容打印到屏幕
- 为什么如果 QWidget 在屏幕上不可见,我只能在运行时向 QWidget 添加元素?
- 对屏幕上绘制的元素进行深度排序