0
/*store a pair of coordinates along with the distance between them
in the format {x1, y1, x2, y2, distance}*/

typedef std::array<double, 5> coord_distance;
typedef std::set<coord_distance> loc_distances;

coord_distance pair_1 = {1,4,5,6, sqrt(pow(5-1,2) + pow(6-4,2))};
coord_distance pair_2 = {7,4,3,8, sqrt(pow(3-7,2) + pow(8-4,2))};
coord_distance pair_3 = {2,9,0,8, sqrt(pow(0-2,2) + pow(8-9,2))};

loc_distances.insert(pair_1);
loc_distances.insert(pair_2);
loc_distances.insert(pair_3);

/*I want to find the element in the set loc_distances with a certain specific x1
and a certain specific x2, then return the distance stored with them*/

If I have a set of arrays that stores a pair of coordinates and the distance between them, I would like to write a function by which I can search in the set to find an element with a specific x1 coordinate and a specific x2 coordinate and return the distance between them, something like:

double get_distance(double x1, double x2, loc_distances const& set){...}

Is there a way to do so?

Ken White
  • 123,280
  • 14
  • 225
  • 444
PileUp120
  • 13
  • 2
  • Try [std::find_if](https://www.cplusplus.com/reference/algorithm/find_if/). – ChrisD Oct 27 '21 at 23:18
  • Agreed ^, but note that this will brute force through the set. There's pretty much nothing you can do to take advantage of `set`'s high-speed look-up if you can't use the key value. – user4581301 Oct 27 '21 at 23:27
  • 1
    In that case you probably want a `std::map` (or `std::multimap`) mapping x1,x2 pairs to the coordinate. And since you are using `double`s see [this](https://stackoverflow.com/questions/17333/what-is-the-most-effective-way-for-float-and-double-comparison) too. – ChrisD Oct 27 '21 at 23:40
  • Thanks for the advice! I refactored my structure using std::map and that helped solve the problem – PileUp120 Oct 28 '21 at 01:26

0 Answers0