I am trying to build a comparator for a map to be used with sort() function. consider a map object called right with an id and coordinates as the basic member. I am trying to sort the elements of this object with euclidean distance. below is the code.
#include <iostream>
#include <vector>
#include <map>
#include <cmath>
#include <algorithm>
namespace NONBCG_DATA_ALGO
{
template<typename T>
T distance(std::vector<T> P1, std::vector<T> P2 , int dim)
{
if ((typeid(T) == typeid(int)) || (typeid(T) == typeid(double)) || (typeid(T) == typeid(float)) )
{
float accum = 0;
for(int i=0; i<dim; i )
{
accum = pow((P2[i]-P1[i]),2);
}
return sqrt(accum);
}
else
{
throw std::invalid_argument("Type should be either int,double or float");
}
}
template<typename T>
class distance_compare_asc_comp_id_2D
{
public:
distance_compare_asc_comp_id_2D(std::vector<T> ipt):Pt(ipt){};
bool operator()(const std::pair<int,std::vector<T>>& p1,const std::pair<int,std::vector<T>>&p2)
{
if ((typeid(T) == typeid(int)) || (typeid(T) == typeid(double)) || (typeid(T) == typeid(float)) )
{
return NONBCG_DATA_ALGO::distance<T>(Pt,p1.second,2) < NONBCG_DATA_ALGO::distance(Pt,p2.second,2);
}
else
{
throw std::invalid_argument("Type should be either int,double or float");
}
}
private:
std::vector<T> Pt;
};
};
int main() {
// Write C code here
std::map<int,std::vector<double>> right;
right.insert(std::pair<int,std::vector<double>>(1,{2,8,3}));
right.insert(std::pair<int,std::vector<double>>(6,{2.5,5.4,3}));
sort(right.begin(),right.end(),NONBCG_DATA_ALGO::distance_compare_asc_comp_id_2D<double>(std::vector<double>{0.0,0.0}));
return 0;
}
I get the following error while building
In file included from /usr/include/c /9/algorithm:62,
from /tmp/wxeRdlKRUn.cpp:6:
/usr/include/c /9/bits/stl_algo.h: In instantiation of 'void std::__sort(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = std::_Rb_tree_iterator<std::pair<const int, std::vector<double> > >; _Compare = __gnu_cxx::__ops::_Iter_comp_iter<NONBCG_DATA_ALGO::distance_compare_asc_comp_id_2D<double> >]':
/usr/include/c /9/bits/stl_algo.h:4899:18: required from 'void std::sort(_RAIter, _RAIter, _Compare) [with _RAIter = std::_Rb_tree_iterator<std::pair<const int, std::vector<double> > >; _Compare = NONBCG_DATA_ALGO::distance_compare_asc_comp_id_2D<double>]'
/tmp/wxeRdlKRUn.cpp:70:122: required from here
/usr/include/c /9/bits/stl_algo.h:1968:22: error: no match for 'operator-' (operand types are 'std::_Rb_tree_iterator<std::pair<const int, std::vector<double> > >' and 'std::_Rb_tree_iterator<std::pair<const int, std::vector<double> > >')
1968 | std::__lg(__last - __first) * 2,
| ~~~~~~~^~~~~~~~~
I really appreciate any help you can provide.
CodePudding user response:
molbdnilo's suggestion of using a vector of pairs fits perfectly for my usage. Thanks, everyone for the help!