2つのベクトルfoo
とbar
が与えられたとき、私はbarの「最も近い」要素にインデックスを含む長さfoo.size()
のベクトルを出力したいと思います。私は車輪を再発明するのが好きではありません - これを簡潔に行うにはSTLアルゴリズムなどがありますか?2つの配列間の最も近い点のインデックス
#include <vector>
#include <cmath>
#include <float.h>
int main() {
vector<double> foo;
vector<double> bar;
// example data setup
double array_foo[] = {0.0, 1.0, 2.0, 3.0, 4.0,
5.0, 6.0, 7.0, 8.0, 9.0};
double array_bar[] = {4.8, 1.5, 12.0};
foo.assign(array_foo, array_foo + 10);
bar.assign(array_bar, array_bar + 3);
// output array
vector<int> indices;
indices.resize(foo.size());
for(int i = 0; i < foo.size(); i++) {
double dist = DBL_MAX;
int idx = 0;
// find index of closest element in foo
for(int j = 0; j < bar.size(); j++) {
if(abs(foo[i] - bar[j]) < dist) {
dist = abs(foo[i] - bar[j]);
idx = j;
}
}
indices[i] = idx;
}
// expected result: indices = [1,1,1,1,0,0,0,0,0,2]
return 0;
}
あなたの 'lower_bound'の説明は少し正確ではありません。'> = '私はlower_boundを排他的に使用します;最も近い値は、その位置または前の値のいずれかになります。 –
彼らはソートされていません - これは私のデータの選択によって暗示された場合は申し訳ありません。 – YXD