【问题标题】:Efficient way of getting the values in a certain area of a 2D vector获取二维向量特定区域中的值的有效方法
【发布时间】:2020-06-21 11:12:49
【问题描述】:

例如,我有一个整数的二维向量,例如:

0,1,4,7,3,7,3,7,7,2
3,6,3,1,7,9,2,8,3,6
1,4,9,3,5,8,3,2,8,5
2,5,8,4,9,3,2,9,0,1
3,6,3,1,7,9,2,8,3,6
1,4,9,3,5,8,3,2,8,5

我想获得另一个二维向量,其中包含水平索引 2 到 5 和垂直索引 1 到 3 的值,我将用 '■' 说明我需要的值。

0,1,4,7,3,7,3,7,7,2
3,6,■,■,■,■,■,8,3,6
1,4,■,■,■,■,■,2,8,5
2,5,■,■,■,■,■,9,0,1
3,6,3,1,7,9,2,8,3,6
1,4,9,3,5,8,3,2,8,5

本例中我想要的 2D 向量:

3,1,7,9,2
9,3,5,8,3
8,4,9,3,2

我需要这非常有效,因为我在卷积神经网络中使用它来获取过滤器当前结束的输入图像区域,并且需要执行数千次。 (在我的例子中,我将使用它从另一个 3D 向量中获取一个 3D 向量,但我认为将其放大应该不会太难,而且使用 2D 向量来解释我的想法要容易得多)

【问题讨论】:

  • 就做吧,如果你在这部分有性能问题,你可以先向我们展示你做了什么。过早优化是万恶之源。
  • “非常有效”的方法是实现一个 2D 矢量抽象,可以将其配置为另一个 2D 矢量的子部分的视图,而不涉及任何类型的复制,类似于 std::string_view 所做的std::strings。不幸的是,就像 C++ 中大多数重要的事情一样,这需要编写一堆代码,这不是 stackoverflow.com 的主题答案。我鼓励你继续阅读你的 C++ 书籍并练习示例问题,直到你获得足够的技能和知识来实现​​这样的事情。
  • FWIW,如果你想要性能,你确实想要一个二维向量。您想使用一维向量并假装它具有多个维度,例如:stackoverflow.com/a/60546369/4342498

标签: c++ vector neural-network 2d conv-neural-network


【解决方案1】:

我已经为你制作了一个从矩阵中获取子矩阵的函数

std::vector<std::vector<int>> subMatrix(std::vector<std::vector<int>>& matrix, 
    unsigned int x, unsigned int y, unsigned int width, unsigned int height) {
    std::vector<std::vector<int>> submatrix;
    for(int i = 0; i < width; i ++) {
        std::vector<int> vect;
        for(int j = 0; j < height; j ++)
            vect.push_back(matrix[i + x][j + y]);
        submatrix.push_back(vect);
    }
    return submatrix;
}

还有另一个显示矩阵的函数:

void showMatrix(std::vector<std::vector<int>>& matrix) {
    for(std::vector<int> vect : matrix) {
        for(int n : vect) {
            std::cout << n << " ";
        }
        std::cout << "\n";
    }
}

这就是我使用它们的方式:

int main(void) {

    std::vector<std::vector<int>> matrix = {
        {0,0,0,0},
        {0,1,0,0},
        {0,0,1,0},
        {0,0,0,0},
    };
    showMatrix(matrix);

    std::cout << "\n";
                                                           //  x, y, width, height
    std::vector<std::vector<int>> submatrix = subMatrix(matrix, 1, 1, 3, 3);
    showMatrix(submatrix);

    return 0;
}

输出:

0 0 0 0
0 1 0 0
0 0 1 0
0 0 0 0

1 0 0
0 1 0
0 0 0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-12
    • 2013-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-13
    • 1970-01-01
    相关资源
    最近更新 更多