检查一对值后,对向量上的lower_bound

时间:2018-06-09 07:10:33

标签: c++ sorting c++11 std-pair lower-bound

我在vector< pair< string,int> >中有一对C++的向量,我希望在字符串值上使用lower_bound,但是附加约束条件的第二个值应该小于或等于给定值。 目前我正在使用比较模板

bool compare(const T &a,const T &b){
if (a.first<=b.first&&b.second<=a.second) return true;
}

但它无法正常工作。 矢量根据pair的第一个值排序。 示例 - &gt;向量具有以下内容:

abcd,1
abcde,4
abcdex,3
abce,2

我想在abc,3上降低点数,因此它应该返回abcd,1,但它会返回abcdex,3。请帮忙。

1 个答案:

答案 0 :(得分:1)

  

std::lower_bound属于binary search算法系列,其中元素使用运算符&lt;对于   第一个版本,第二个版本的comp。范围内的元素   已按照相同标准(运算符&lt;或comp)进行排序,或者至少按val进行分区。

这意味着,您需要按照首先提到的方式对向量进行排序,以便按预期行事std::lower_bound

一旦你对数组的矢量进行了排序,你提到使用compare仿函数/(我把它作为一个lambda),你可以使用std::lower_bound

SEE LIVE HERE

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

int main()
{
   using Pair = std::pair< std::string, int> ;
   std::vector< Pair > vec =
   {
      {"abcd", 1},
      {"abcde", 4},
      {"abcdex", 3},
      {"abce", 2}
   };
   // define the compare lambda/ functor accordingly
   auto  compare = [](const Pair &lhs, const Pair &rhs)->bool
   { return (rhs.second > lhs.second) ? false: lhs.first <= rhs.first;  };

   // sorted the vector according to the custom compare
   std::sort(vec.begin(), vec.end(), compare);

   auto getLower = std::lower_bound(vec.begin(), vec.end(), Pair("abc",3), compare);

   if(getLower != vec.cend()) std::cout << getLower->first << " " << getLower->second;

  return 0;
}

输出

abcd 1

注意:为了使用std::lower_bound,您需要根据您首先应用下限(这是基本的)的方式对矢量进行排序。

但是,在您的排序模式中,std::lower_bound不知道该对(int)天气的第二个值是否正确排序了数组。换句话说,即使您事先对提到的内容进行排序,std::lower_bound也无法为您提供所需的结果,因为您以Pair和{{Pair.first的方式对Pair.second进行排序1}}以相反的顺序。

因此,我建议您使用std::find_if,它将线性搜索元素,并且必须使用与谓词相同的比较向导。如果事先相应地对矢量进行了排序(如你所提到的),那么它应该给你一个合适的结果。

// sort before
checkPair =  Pair("abc",3);
auto getLower = std::find_if( vec.begin(), vec.end(), [&checkPair](const Pair &ele) -> bool
{
   if(currPair == ele ) return true;

   return (checkPair.first >= ele.first      //--> "whose value is greater than or equal to the given string
          && ele.second < checkPair.second); //--> second value is less than a number
});

(getLower != vec.cend()) ? 
         std::cout << getLower->first << " " << getLower->second:
         std::cout << "Nothing found";
相关问题