在检查对的一个值后,lower_bound对向量

lower_bound on a vector of pair after checking one value of pair

本文关键字:lower bound 向量 检查 一个      更新时间:2023-10-16

我有一个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;
}

但它无法正常工作。 向量根据对的第一个值进行排序。 示例->矢量具有以下内容:

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

我想lower_boundabc,3所以它应该返回abcd,1但它正在返回abcdex,3.请帮忙。

std::lower_bound属于binary search算法家族,其中元素使用运算符进行比较<第一个版本,第二个版本。范围内的元素>应已根据相同的标准(运算符

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

一旦你以方式对数组向量进行了排序,你提到使用compare函子/(我把它做成一个 lambda(,你可以使用std::lower_bound.

在这里查看直播

#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不知道数组是否正确排序的 pair(int( 的第二个值。换句话说,即使您对事先提到的内容进行相应的排序,std::lower_bound也无法为您提供所需的结果,因为您对Pair进行排序的方式是Pair.firstPair.second顺序相反。

因此,我建议您使用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";