c++ - 如何在 C++ 中的矩阵中搜索 vector 以及使用哪种算法?

标签 c++ arrays algorithm matrix

假设我有一个矩阵和一个由 给出的 vector 。如何执行二进制搜索之类的搜索算法来返回索引? 示例:

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中查找 vector a2,返回值为6 非常感谢

最佳答案

您可以将 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

关于c++ - 如何在 C++ 中的矩阵中搜索 vector 以及使用哪种算法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33031108/

相关文章:

algorithm - 语音内存密码生成算法

c++ - 在 Windows XP/Server 2003 下将新旧本地时间转换为 UTC

php - array_splice 保留键

c - 我怎么能在C中插入不超过5个句子并且每个句子不超过50个字母

php - 获取数组作为 AJAX 的响应

最适合矩形的算法

c# - 在 C# 应用程序中构建静态库

c++ - 如何在类级别专门化模板类

c++ - 是否有任何示例表明三重冒号 (:::) 是 C++ 代码中的有效语法?

algorithm - 最大积子序列