首页 > 解决方案 > lower_bound() 给出意想不到的结果

问题描述

我写了一个代码,我需要lower_bound从平方数序列中找到。但下限给了我的结果upper_bound

这是我的代码和编译器链接: http ://cpp.sh/3cppb

// Example program
#include <iostream>
#include <string>
#include <algorithm>

int main()
{
   std::vector<int> v{ 1, 4, 9, 16, 25 }; // all the square numbers
   
   int x = std::lower_bound(v.begin(), v.end(), 5) - v.begin() ;
   
   std:: cout<<"Postion "<<x<< "  value  "<<v[x] <<std::endl; //getting output for upperbound
   
}

输出:

Postion 2  value  9

预期产出

Postion 1  value  4

标签: c++stlruntime-errorlower-bound

解决方案


std::lower_bound将迭代器返回到大于或等于目标值的第一个元素:

返回一个迭代器,该迭代器指向范围 [first, last) 中不小于(即大于或等于)值的第一个元素,如果没有找到这样的元素,则返回 last。

9第一个大于或等于的值5一样(当然,它更大),结果是完全正确的。

如果你试图找到一个已经在v, like中的元素9,那么你会得到std::lower_bound和不同的结果std::upper_bound

std::distance(begin(v), std::lower_bound(begin(v), end(v), 9)); // 2
std::distance(begin(v), std::upper_bound(begin(v), end(v), 9)); // 3

推荐阅读