I was wondering if there is a nice way to sort a vector based on some external value. For instance, I have a vector of k nearest neighbors to a point. I want to sort this vector based on their distance to the query point. The query point is not included in the results, and std::sort allows you to define a comparison function for two elements in the vector (rather than each element vs a fixed point). Is there any pre-built method to do this sort of sort? Or would I need to build my own custom sorting algorithm? Thanks
Recommended: Please try your approach on {IDE} first, before moving on to the solution. Approach: The idea is to store each element at its distance from the given point P in a pair and then sort all the elements of the vector according to the distance stored. Sort the array of distance and print the points based on the sorted distance.
C++ Server Side Programming Programming. Sorting a vector in C++ can be done by using std::sort (). It is defined in<algorithm> header. To get a stable sort std::stable_sort is used. It is exactly like sort () but maintains the relative order of equal elements. Quicksort (), mergesort () can also be used, as per requirement.
Print “Elements before sorting”. for (const auto &i: v) print all the values of variable i. Print “Elements after sorting”. Call sort (v.begin (), v.end ()) function to sort all the elements of the v vector. for (const auto &i: v) print all the values of variable i. End.
If you have some class Point and the point you want to sort against is and you had some function dist that took 2 Point and returned the distance (e.g. Euclidean distance) like Show activity on this post. You don't need a different sorting algorithm. std::sort works perfectly fine with user-provided orders.
If you have some class Point
and the point you want to sort against is
Point p
Also assume that points
is defined as
std::vector<Point> points;
and you had some function dist
that took 2 Point
and returned the distance (e.g. Euclidean distance) like
double dist(const Point& lhs, const Point& rhs)
{
// compute Euclidean distance or whatever
}
Then you can use std::sort
with a lambda function
std::sort(begin(points),
end(points),
[p](const Point& lhs, const Point& rhs){ return dist(p, lhs) < dist(p, rhs); });
Edit
If you do not have C++11 access, you need to define a functor
struct DistanceFunc
{
DistanceFunc(const Point& _p) : p(_p) {}
bool operator()(const Point& lhs, const Point& rhs) const
{
return dist(p, lhs) < dist(p, rhs);
}
private:
Point p;
};
Then you can sort in a similar way
std::sort(points.begin(), points.end(), DistanceFunc(p));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With