Shi*_*bli 10 c++ lambda stdvector std-pair
我想找到std::lower_bound的一个的std::vector的std::pair根据的第二与拉姆达元素.
std::vector < std::pair <int, double> > vec;
vec.resize(5);
auto it = std::lower_bound(vec.begin(), vec.end(), lambda);
// what is that lambda here?
Run Code Online (Sandbox Code Playgroud)
Bor*_*der 18
你在这里缺少一个参数,std::lower_bound接受一个开始和结束迭代器,一个值(这是你错过的),最后可以取一个lambda.
#include <algorithm>
#include <vector>
int main()
{
typedef std::pair<int, double> myPair; // typedef to shorten the type name
std::vector <myPair> vec(5);
myPair low_val; // reference value (set this up as you want)
auto it = std::lower_bound(vec.begin(), vec.end(), low_val,
[](myPair lhs, myPair rhs) -> bool { return lhs.second < rhs.second; });
}
Run Code Online (Sandbox Code Playgroud)
lower_bound的参考页面在这里.
的目的lower_bound是找到元素将要到达的位置。因此,您必须指定该元素。如果只想按第二个伙伴排序,则只需为此指定一个值:
std::vector<std::pair<int, double>> vec = /* populate */ ; // must be sorted!
double target = 1.3;
auto it = std::lower_bound(vec.begin(), vec.end(), target,
[](std::pair<int, double> const & x, double d)
{ return x.second < d; });
Run Code Online (Sandbox Code Playgroud)
请注意,向量必须根据相同的谓词进行排序,因此您可能希望更永久地存储谓词:
auto lb_cmp = [](std::pair<int, double> const & x, double d) -> bool
{ return x.second < d; };
auto sort_cmp = [](std::pair<int, double> const & x,
std::pair<int, double> const & y) -> bool
{ return x.second < y.second; };
std::sort(vec.begin(), vec.end(), sort_cmp);
auto it = std::lower_bound(vec.begin(), vec.end(), target, lb_cmp);
Run Code Online (Sandbox Code Playgroud)