在检查对的一个值后,lower_bound对向量
lower_bound on a vector of pair after checking one value of pair
我有一个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.first
和Pair.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";
- 空集"Out of bound iterator"
- 将张量的"lower diagonal"映射到矩阵,作为将矩阵的下三角形部分提取到向量的推广
- 为什么<<低;和 cout<<v.begin;单独给出错误,但 cout <<(lower.begin());没有给出任何错误,并使代码易于编译
- 使用多个文件时"array bound is not an integer constant before ']' token"
- "A reference may be bound only to an object",为什么"const int &ref = 3;"有效?
- 如何修复"reference cannot be bound to dereferenced null pointer"警告
- 当你有一个像 ::lower 这样的参数时,这在C++中是什么意思
- GCC 检测"subindex out of bound"错误
- 如果我没有得到分段错误,如何找到"index out of bound"
- 一个程序将字符串Upper char更改为Lower char得到错误
- std:: lower的行为在不同的语言环境中是如何变化的?
- 在main中声明Array之前,Array bound不是整型常量
- 获取错误"array bound is not an integer constant before ']' token"
- 如何在C或c++中获得与Java中的toLowerCase或Python中的string.lower()相同的结果
- 在运行时创建结构时"array bound is not an integer constant"