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.


#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);
}
Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

Categories

%d bloggers like this: