How to return more than one type from a function?

Background. In VBA in Excel, I created a function that calculates the shortest distance between two lines (vectors). This function returns the visible intersection point and the actual distance between them. To make this work, I finished distributing the array, and then sorted out what happened next. It works, but it is inconvenient to read and work.

In C ++, I made a similar function that returns this point.

struct point3D
{ 
double x,y,z;
}
point3D findIntersect(const vec3& vector1, const vec3& vector2)
{
// Do stuff...
return point;
}

Problem: I want to return the length as well, since it uses parts of the original calculation. However, most of the time I want only a point.

Possible solutions that I have reviewed are as follows:

Write a separate function for the distance. A lot of extra work when I want both of them.

  • Create your own structure for this function. It seems a bit overkill.
  • , VBA. .
  • . . .
  • , function(const argin1, const argin2, argout&, argout2&). ! , , .

, , . a point3D a double.

- ?

+4
6

, , , . , NULL, NULL, , .

point3D findIntersect(const vec3 &v1, const vec3 &v2, double *dist = NULL) {
  // ...
  if (dist) {
    // find the distance and store in *dist
  }
  return ... ;
}
+2

++ , , . point3D length "", :

point3D findIntersect(const vec3& vector1, const vec3& vector2) {
    double ignore;
    return findIntersect(vector1, vector2, ignore);
}
point3D findIntersect(const vec3& vector1, const vec3& vector2, double &length) {
    ... // Implementation goes here
}

, , , , , . , .

+1

Straustup Sutter tuple/tie : F.41: out-

Point3D point3D;
double distance;

std::tie(point3D, distance) = findIntersect(/*..params..*/);

:

std::tuple<Point3D, double> findIntersect(/*..params..*/)
{
    Point3D point3D;
    double distance;

    // calculate point3D & distance

    return std::make_tuple(point3D, distance);
} 
+1

std::pair<point3D, double>. std::tuple, . ( , , , , .)

0

.

std::pair<point3D, double> findIntersect(const vec3& vector1, const vec3& vector2);
0

I still think that you can and should create a structure for your code (if your code is not in real time ..) Chips are very common and give you the flexibility and flexibility if you need to spend your code. To be dependent on this pair of key values ​​in your code, and then implement in a few months, that you need to change it in 10 places ... :)

-2
source

Source: https://habr.com/ru/post/1609138/


All Articles