如何在C ++中搜索矩阵中的向量以及哪种算法?

时间:2015-10-09 06:14:21

标签: c++ arrays algorithm matrix

假设我有一个矩阵和一个给定的向量。如何执行二进制搜索等搜索算法来返回索引? 例如:

const int V_SIZE = 10,H_SIZE = 7;
   int a1[V_SIZE][H_SIZE] = {
                                {1,2,0,0,0,0,0},
                                {1,3,0,0,0,0,0},
                                {2,2,4,0,0,0,0},
                                {2,2,6,0,0,0,0},
                                {3,2,4,7,0,0,0},
                                {4,1,3,5,9,0,0},
                                {4,1,4,6,8,0,0},
                                {4,2,3,4,7,0,0},
                                {5,2,3,5,7,8,0},
                                {6,1,3,4,5,7,10}
                            }; // sorted
  int a2 [H_SIZE] = {4,1,3,5,9,0,0};

在矩阵a1中搜索向量a2,返回值为6 非常感谢

3 个答案:

答案 0 :(得分:1)

您可以将2D std::arraystd::lower_bound结合使用:

  const int V_SIZE = 10,H_SIZE = 7;
  std::array<std::array<int, H_SIZE>, V_SIZE> a1 {
                                {{{1,2,0,0,0,0,0}},
                                {{1,3,0,0,0,0,0}},
                                {{2,2,4,0,0,0,0}},
                                {{2,2,6,0,0,0,0}},
                                {{3,2,4,7,0,0,0}},
                                {{4,1,3,5,9,0,0}},
                                {{4,1,4,6,8,0,0}},
                                {{4,2,3,4,7,0,0}},
                                {{5,2,3,5,7,8,0}},
                                {{6,1,3,4,5,7,10}}
                            }}; // sorted

  std::array<int, H_SIZE> a2 {{4,1,3,5,9,0,0}};

  int idx = std::lower_bound(std::begin(a1), std::end(a1), a2) - std::begin(a1);

LIVE DEMO

答案 1 :(得分:0)

如果矩阵按第一个数字排序,您可以使用二进制搜索来查找近似索引。然后,您必须返回,直到找到以向量中相同数字开头的第一行,以及转发以查找以相同数字开头的最后一行。然后你循环遍历向量,搜索你所拥有的行范围内的第二个,第三个等号码的匹配。

答案 2 :(得分:0)

使用std :: array?

这样的事情怎么样?
template <int HSIZE>
bool operator<(const std::array<int, HSIZE> &lhs, const std::array<int, HSIZE> &rhs)
{
    for (int i = 0; i < HSIZE; i++)
        if (lhs[i] != rhs[i])
            return lhs[i] < rhs[i];
    return false;
}

std::array<int, 7> a1[] = 
{
    { 1, 2, 0, 0, 0, 0, 0 },
    { 1, 3, 0, 0, 0, 0, 0 },
    { 2, 2, 4, 0, 0, 0, 0 },
    { 2, 2, 6, 0, 0, 0, 0 },
    { 3, 2, 4, 7, 0, 0, 0 },
    { 4, 1, 3, 5, 9, 0, 0 },
    { 4, 1, 4, 6, 8, 0, 0 },
    { 4, 2, 3, 4, 7, 0, 0 },
    { 5, 2, 3, 5, 7, 8, 0 },
    { 6, 1, 3, 4, 5, 7, 10 } 
};

void search(void)
{
    std::array<int, 7> a2 = { 4, 1, 3, 5, 9, 0, 0 };
    std::array<int, 7> *a1_end = a1 + sizeof(a1) / sizeof(std::array<int, 7>);
    std::array<int, 7> *it = std::lower_bound(a1, a1_end, a2);

}