Posted by: sureshamrita | March 8, 2011

Nearest neighbour in C++

Using the min_element algorithm of the standard library, it is possible to write a nearest neighbor code as shown below.

using namespace std;
class NN{
  NN(int x):data(x){}
  bool operator()(int a, int b){
    return abs(a-data) < abs(b-data);
  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);

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s


%d bloggers like this: