C++集查找值较小但更接近x
C++ set find value smaller but closer to x
我查看了<set>
的C++STL中的lower_bound
和upper_bound
。然而,我找不到一种方法来获得与集合中另一个值最接近的值(从下面开始)。有没有一种简单的方法可以得到它,或者我必须迭代集合?
举个例子,假设我的集合包含以下整数3 4 7 9
,然后是closest(6) = 4
和closest(4) = 4
。
std::upper_bound
返回一个大于给定值的元素,因此在您的情况下,您必须将其递减才能获得之前的值。
//Returns value of element before 'num'
int closest = *--set.upper_bound(num);
我本以为是closest(6) = 7
,因为7
比4
更接近6
。如果要获得7
,则必须计算相邻值之间的差异并进行比较。
//Calculate closest value to 'num' in a std::set<int>
int closest(std::set<int>& set, int num)
{
//Get iterator to element greater than 'num'
auto it = set.upper_bound(num);
//Check if 'it' is the 'end' iterator
if (it == std::end(set))
return 0;
int valueLeft = *it--; //Get value of the greater element
int valueRight = *it; //Get value of the element before (due to post-decrement)
//Compare diffence between value less and num, and value greater and num
if (valueLeft - num > num - valueRight)
return valueRight;
else
return valueLeft;
}
std::set<int> set{ 3, 4, 7, 9 };
int a = closest(set, 6); //Returns '7'
int b = closest(set, 4); //Returns '4'
试试这个通用算法:
template <typename Set>
typename Set::const_iterator
find_closest(Set const & s, typename Set::value_type const & val)
{
auto a = s.begin(), b = s.end(), it = s.lower_bound(val);
if (it == b)
{
if (it != a) --it;
return it;
}
auto nt = std::next(it);
if (nt == b) return it;
return val - *it < *nt - val ? it : nt;
}
//included all libraries
auto find(int l, set<int>&s){
auto it=s.lower_bound(l);
if(s.size() and *s.begin()<=l){ //check any smaller element present in set
auto it=s.upper_bound(l);
it=prev(it);
}
return it;
}
相关文章:
- 正在查找文档以获得PS4平台的C++中的设备信息
- 在C++中查找文件
- 模板元程序查找相似的连续类型名称
- 在UNIX系统中使用DIR查找文件的字节大小
- 查找最接近的大于当前数字的数字的索引
- 查找索引的最接近的真实值
- 在结构向量中查找最接近的值
- 查找整数数组中最接近的数字
- 使用非线性级数查找最接近的值
- 查找记录等于或最接近使用向量C 的平均值
- 从均匀网格中查找最接近的数字
- 查找从列表到一个参考列表的最接近点
- C++集查找值较小但更接近x
- 在数组中查找一个变量,哪个和最接近目标和
- 在std::映射中查找最接近或精确的关键字
- 使用数组查找最接近的数字C++,浮点
- 查找数组中与另一个给定数字最接近的数字
- 在两个数组中查找最接近的数字
- 在c++中查找小于特定整数值的最接近的浮点值
- C++11:`错误:代码中')'标记之前应有主表达式',用于行扫描以查找最接近的对