Using the min_element algorithm of the standard library, it is possible to write a nearest neighbor code as shown below.
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class NN{
public:
NN(int x):data(x){}
bool operator()(int a, int b){
return abs(a-data) < abs(b-data);
}
private:
int data;
};
using namespace std;
int main(){
vector<int> data(10);
for(int i = 0; i < 10; i++)data[i] = i;
NN n(4);
cout << *min_element(data.begin(),data.end(),n);
}
Recent Comments