c++ - Implementing the [B,C]=f(A) syntax (function f acting on an array with two or more output arrays) -
i have question extension of other 2 questions have posted:
implementing b=f(a), b , arrays , b defined
and
implementing b=f(a) syntax move assignment
suppose have array a. want create function f acts on a , returns 2 other arrays b , c, enabling following matlab-like syntax
[b,c]=f(a); is possible in c++?
solution following leemes' answer
#include <tuple> using std::tie; std::tuple<typeofb,typeofc> f(const matrix<t1>&a,const matrix<t2>&a) { // instruction declaring , defining b_temp , c_temp return std::make_tuple(b_temp,c_temp); } int main( int argc, char** argv) { // instruction declaring a, b , c tie(b,c)=f(a); // stuff return 0; } everything works when changing std::tuple , make_tuple std::pair , std::make_pair particular case (only 2 outputs).
in general, if want return multiple values, have little work-around, since c++ doesn't allow out of box.
the first option return std::pair containing both values. can use std::tie in return statement if have c++11 available, this:
std::tie(b, c) = f(a); (note: c++11 has std::tuple more 2 values.)
or can pass 2 target variables reference, function call becomes (works without c++11):
f(a, b, c); to make function call more "verbose" (some people don't can't tell f changes b , c looking @ single line of code) can use pointers instead of references. function call this:
f(a, &b, &c); another option use simple "container" multiple return values. useful in particular if simple pair or tuple don't give values particular meaning. best option use consistently in code calls f (don't use separate arrays b , c). use if fits nicely rest of code design.
struct twoarrays { int b[100]; int c[100]; }; twoarrays result = f(a);
Comments
Post a Comment