给定两个向量foo
和bar
,我想输出一个长度为foo.size()
的向量,该向量包含条的“最接近”元素的索引。我不喜欢重新发明轮子 - 是否有任何STL算法或以其他方式简洁明了?两个阵列之间的最近点索引
#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