3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ソート済み配列から指定した値に最も近い値を取り出す

Posted at

lower_boundである数値を超えるイテレータを取り出した後,その1個手前の要素を取り出す.
さらに,2つの要素との距離を取り,最も小さい方を返す.
STLだとできないかなぁとか思っていたけれども,思いのほかできてしまったので嬉しい.
それだけ.

# include <iostream>
# include <vector>
# include <algorithm>
using namespace std;

int main()
{
	std::vector<float> v;
	for (int i = 0; i < 10; ++i) v.push_back(i);

	float val = 11;

	int back = std::lower_bound(v.begin() + 1, v.end() - 1, val) - v.begin();
	int front = back - 1;
	
	float x = v[front] - val;
	float y = v[back] - val;

	int near;
	if (x * x < y * y)
		near = front;
	else
		near = back;
	cout << v[near] << endl;

	return 0;
}
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?