Given two vectors foo and bar, I want to output a vector of length foo.size() containing the index to the “closest” element of bar. I don’t like reinventing the wheel – are there any STL algorithms or otherwise to do this concisely?
#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;
}
This exact algorithm doesn’t exist, but you could implement it in an idiomatic STL way by using
std::min_elementand a custom functor:Your algorithm would then be replaced with:
I tested with your input and got your expected results.