如何找到向量中第一个比整数X小的元素? (C ++) [英] How to find the first smaller element than an integer X in a vector ? (c++)

查看:131
本文介绍了如何找到向量中第一个比整数X小的元素? (C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下向量{10 10 10 20 20 20 30 30} 并且我想要一个函数返回= X的整数的位置,或者直接返回X之后的较小元素,例如,如果我搜索11,我希望该函数返回2,因为第二个element(10)是第一个较小的元素向量中的11个元素.
我尝试使用lower_bound,但这不起作用.

If I have the following vector {10 10 10 20 20 20 30 30} and I want a function to return the position of the integer that = X or directly the smaller element after X , like for example if I am searching for 11 I want the function to return 2 since the 2nd element(10) is the first smaller element than 11 in the vector.
I tried using lower_bound but that doesn't work.

int myints[] = {10,20,30,30,20,10,10,20};
vector<int> v(myints,myints+8);           // 10 20 30 30 20 10 10 20
vector<int>::iterator low,up;

sort (v.begin(), v.end());                // 10 10 10 20 20 20 30 30

low=lower_bound (v.begin(), v.end(), 11); //
up= upper_bound (v.begin(), v.end(), 11); //

cout << "lower_bound at position " << int(low- v.begin()) << endl;
cout << "upper_bound at position " << int(up - v.begin()) << endl;

return 0;

此代码输出:

this code outputs:

lower_bound at position 3
upper_bound at position 3

推荐答案

cppreference通知我std::lower_bound

cppreference informs me that std::lower_bound

返回一个迭代器,该迭代器指向[strong,不小于]

std::upper_bound

返回一个迭代器,该迭代器指向[strong,大于值]

在这种情况下,给定一个包含10 10 10 20 20 20 30 30的向量,我希望两个函数都指向第一个20,它位于向量的位置3上,并且确实是您两次都得到的结果.如果您反而要求输入20,则std::lower_bound将返回指向向量中第一个20的迭代器(位置3)...第一个数字不少于20,并且得到的结果与要求11.但是,在这种情况下,std::upper_bound将返回指向第一个30(位置6)的迭代器,该迭代器是大于20的第一个值.

In this case, given a vector containing 10 10 10 20 20 20 30 30 I would expect both functions to point at the first 20, which sits at position 3 in the vector and is indeed the result you got both times. If you had instead asked for 20, std::lower_bound would return an iterator pointing to the first 20 in the vector (position 3)... the first number not less than 20 and the same result you'd get when asking for 11. In this case though, std::upper_bound would return an iterator pointing at the first 30 (position 6), which is the first value greater than 20.

只需将迭代器后退一个即可获得小于目标数字的最后一个值,std::prev是实现此目标的一种方法.

Just move the iterator back one to get the last value less than your target number, std::prev is one way to do that.

这篇关于如何找到向量中第一个比整数X小的元素? (C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆