【问题标题】:Searching lexicographically sorted vector<vector <int> > in c++在c ++中搜索按字典顺序排序的向量<vector <int> >
【发布时间】:2015-07-01 04:26:33
【问题描述】:

我需要按字典顺序对vector&lt;vector&lt;int&gt; &gt; vecOfVectors; 进行排序。

所以,我在按字典顺序排序之前的 vecOfVectors 是:

((0,100,17,2),(2,3,1,3),(9,92,81,8),(0,92,92,91),(10,83,7,2),(1,2,3,3))

为此,我使用以下功能:

std::sort(vecOfVectors.begin(),vecOfVectors.end(),lexicographical_compare);

所以,按字典顺序排序后的 vecOfVectors 现在是:

((0,92,92,91),(0,100,17,2),(1,2,3,3),(2,3,1,3),(9,92,81,8),(10,83,7,2))

现在给定一个向量,我需要在这个排序的 vecOfVectors 中搜索它的位置——像二分搜索这样的东西会很好用。 c++ stl 中是否有一些内置函数可用于执行二进制搜索?

例如: (0,92,92,91)的位置为0; (0,100,17,2) 的位置是 1; (1,2,3,3) 的位置是 2; (2,3,1,3) 的位置是 3; (9,92,81,8) 的位置是 4; (10,83,7,2) 的位置是 5。

【问题讨论】:

  • 不需要任何二分查找,你可以创建一个函数 compare(vector,vector) 来判断其中哪个是字典顺序的。
  • @MadhuKumar 听起来不错,请您借助示例进行解释
  • 您是否尝试过在网上搜索 C++ 中的二进制搜索算法?

标签: c++ sorting c++11 vector stl


【解决方案1】:

不用加lexicographical_compare,已经是比较向量的方式了。

根据您正在寻找std::lower_boundstd::upper_boundstd::binary_searchstd::equal_range 的具体用例,所有这些都在排序向量上运行。

下面是您的数据和 c++11 的完整示例。它构造你的向量,对其进行排序(显示你提到的顺序),然​​后在向量中找到一个值。

#include <vector>
#include <iostream>
#include <algorithm>

void print(const std::vector<int> & v) {
    std::cout<<"(";
    for(auto x=v.begin(); x!=v.end(); ++x) {
        std::cout<<*x<<",";
    }
    std::cout<<")";
}

void print(const std::vector<std::vector<int>> & v) {
    std::cout<<"(";
    for(auto x=v.begin(); x!=v.end(); ++x) {
        print(*x);
        std::cout<<",";
    }
    std::cout<<")"<<std::endl;
}

int main() {

    std::vector<std::vector<int>> v {
        {0,100,17,2},
        {2,3,1,3},
        {9,92,81,8},
        {0,92,92,91},
        {0,92,92,91},
        {10,83,7,2},
        {1,2,3,3}
    };

    print(v);

    std::sort(v.begin(), v.end());

    print(v);

    std::vector<int> key = { 0,100, 17, 2 };

    auto it = std::lower_bound(v.begin(), v.end(), key);
    if(it!=v.end() && key==*it) {
        std::cout<<"Found it"<<std::endl;
    } else {
        std::cout<<"Not found"<<std::endl;
    }

}

【讨论】:

  • 好的,谢谢..你能用矢量的例子来说明这一点
  • 你忘了std::equal_range
  • it 可以是.end(),在这种情况下您不能取消引用它。你必须检查if (it != vecOfVector.end() &amp;&amp; *i == key) ...
  • 在 std::sort(v.begin(), v.end());我需要给 lexicographic_compare
  • @JannatArora 不,你不知道。 不用加lexicographical_compare,已经是比较向量的方式了。
【解决方案2】:

正如我在 cmets 中所说的创建函数:

bool compare(vector<int> A,vector<int> B)
{
  int i=0;
  while(i<(A.size()<B.size())?A.size():B.size())
    {
      if(A[i]<B[i])
        {
          return 1;
        }
      else if(A[i]==B[i])
        {
         i++;
        }
      else
        {
          return 0;
        }
      }
 return 0;
}

【讨论】:

  • 是 A.size() 的 5 倍
  • 是的,你可以用 A.size() 替换 5
  • Downvoted:仅适用于长度为 5 的固定向量。向量已经有一个重载的operator&lt;,可以按字典顺序进行比较
  • 对不起,不是真的。它仅适用于int。充分概括这一点,您将重新发明operator&lt;,这是进行向量比较的惯用且万无一失的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-24
  • 1970-01-01
  • 2019-01-07
相关资源
最近更新 更多