Related
I have a function which calculates the first derivative dy/dx for discrete values y(x) stroed as std::vector:
vector<double> CalcDerivative(vector<double>&y, vector<double>&x) {...}
Often the spacing dx is constant so it would be more efficient to pass a double to this function instead of vector<double> as argument x.
I tried to accomplish this with std::variant. The drawback with std::variant is however, that it cannot handle references so the vector x has to be copied while being passed as a variant to the function.
For now I solved the problem by defining two functions with overloaded arguments. But I wonder whether there is a more elegant solution which won't duplicate the code for the two cases (x as double or as vector<double>).
One possible solution might be to define the "worker" function such that it is independent of the "number of passed doubles". For this purpose, std::span is suitable. The exemplary solution might look like:
std::vector<double> CalcDWorker(
std::span<const double> y, std::span<const double> x)
{
... // x.size() == 1 indicates uniform spacing
}
std::vector<double> CalcDerivative(
const std::vector<double>& y, const std::vector<double>& x)
{
return CaclDWorker({y.begin(), y.end()}, {x.begin(), x.end()});
}
std::vector<double> CalcDerivative(
const std::vector<double>& y, double x)
{
return CaclDWorker({y.begin(), y.end()}, {&x, 1});
}
It requires C++20, but there are third-party span implementations available also for earlier C++ versions (such as the one provided by Boost).
Live demo: https://godbolt.org/z/n6adEKWes
Is there a preferred way to return multiple values from a C++ function? For example, imagine a function that divides two integers and returns both the quotient and the remainder. One way I commonly see is to use reference parameters:
void divide(int dividend, int divisor, int& quotient, int& remainder);
A variation is to return one value and pass the other through a reference parameter:
int divide(int dividend, int divisor, int& remainder);
Another way would be to declare a struct to contain all of the results and return that:
struct divide_result {
int quotient;
int remainder;
};
divide_result divide(int dividend, int divisor);
Is one of these ways generally preferred, or are there other suggestions?
Edit: In the real-world code, there may be more than two results. They may also be of different types.
In C++11 you can:
#include <tuple>
std::tuple<int, int> divide(int dividend, int divisor) {
return std::make_tuple(dividend / divisor, dividend % divisor);
}
#include <iostream>
int main() {
using namespace std;
int quotient, remainder;
tie(quotient, remainder) = divide(14, 3);
cout << quotient << ',' << remainder << endl;
}
In C++17:
#include <tuple>
std::tuple<int, int> divide(int dividend, int divisor) {
return {dividend / divisor, dividend % divisor};
}
#include <iostream>
int main() {
using namespace std;
auto [quotient, remainder] = divide(14, 3);
cout << quotient << ',' << remainder << endl;
}
or with structs:
auto divide(int dividend, int divisor) {
struct result {int quotient; int remainder;};
return result {dividend / divisor, dividend % divisor};
}
#include <iostream>
int main() {
using namespace std;
auto result = divide(14, 3);
cout << result.quotient << ',' << result.remainder << endl;
// or
auto [quotient, remainder] = divide(14, 3);
cout << quotient << ',' << remainder << endl;
}
For returning two values I use a std::pair (usually typedef'd). You should look at boost::tuple (in C++11 and newer, there's std::tuple) for more than two return results.
With introduction of structured binding in C++ 17, returning std::tuple should probably become accepted standard.
Personally, I generally dislike return parameters for a number of reasons:
it is not always obvious in the invocation which parameters are ins and which are outs
you generally have to create a local variable to catch the result, while return values can be used inline (which may or may not be a good idea, but at least you have the option)
it seems cleaner to me to have an "in door" and an "out door" to a function -- all the inputs go in here, all the outputs come out there
I like to keep my argument lists as short as possible
I also have some reservations about the pair/tuple technique. Mainly, there is often no natural order to the return values. How is the reader of the code to know whether result.first is the quotient or the remainder? And the implementer could change the order, which would break existing code. This is especially insidious if the values are the same type so that no compiler error or warning would be generated. Actually, these arguments apply to return parameters as well.
Here's another code example, this one a bit less trivial:
pair<double,double> calculateResultingVelocity(double windSpeed, double windAzimuth,
double planeAirspeed, double planeCourse);
pair<double,double> result = calculateResultingVelocity(25, 320, 280, 90);
cout << result.first << endl;
cout << result.second << endl;
Does this print groundspeed and course, or course and groundspeed? It's not obvious.
Compare to this:
struct Velocity {
double speed;
double azimuth;
};
Velocity calculateResultingVelocity(double windSpeed, double windAzimuth,
double planeAirspeed, double planeCourse);
Velocity result = calculateResultingVelocity(25, 320, 280, 90);
cout << result.speed << endl;
cout << result.azimuth << endl;
I think this is clearer.
So I think my first choice, in general, is the struct technique. The pair/tuple idea is likely a great solution in certain cases. I'd like to avoid the return parameters when possible.
std::pair<int, int> divide(int dividend, int divisor)
{
// :
return std::make_pair(quotient, remainder);
}
std::pair<int, int> answer = divide(5,2);
// answer.first == quotient
// answer.second == remainder
std::pair is essentially your struct solution, but already defined for you, and ready to adapt to any two data types.
There are a bunch of ways to return multiple parameters. I'm going to be exhastive.
Use reference parameters:
void foo( int& result, int& other_result );
Use pointer parameters:
void foo( int* result, int* other_result );
which has the advantage that you have to do a & at the call-site, possibly alerting people it is an out-parameter.
Write an out<?> template and use it:
template<class T>
struct out {
std::function<void(T)> target;
out(T* t):target([t](T&& in){ if (t) *t = std::move(in); }) {}
out(std::optional<T>* t):target([t](T&& in){ if (t) t->emplace(std::move(in)); }) {}
out(std::aligned_storage_t<sizeof(T), alignof(T)>* t):
target([t](T&& in){ ::new( (void*)t ) T(std::move(in)); } ) {}
template<class...Args> // TODO: SFINAE enable_if test
void emplace(Args&&...args) {
target( T(std::forward<Args>(args)...) );
}
template<class X> // TODO: SFINAE enable_if test
void operator=(X&&x){ emplace(std::forward<X>(x)); }
template<class...Args> // TODO: SFINAE enable_if test
void operator()(Args...&&args){ emplace(std::forward<Args>(args)...); }
};
then we can do:
void foo( out<int> result, out<int> other_result )
and all is good. foo is no longer able to read any value passed in as a bonus.
Other ways of defining a spot you can put data can be used to construct out. A callback to emplace things somewhere, for example.
We can return a structure:
struct foo_r { int result; int other_result; };
foo_r foo();
whick works ok in every version of C++, and in c++17 this also permits:
auto&&[result, other_result]=foo();
at zero cost. Parameters can even not even be moved thanks to guaranteed elision.
We could return a std::tuple:
std::tuple<int, int> foo();
which has the downside that parameters are not named. This permits the c++17:
auto&&[result, other_result]=foo();
as well. Prior to c++17 we can instead do:
int result, other_result;
std::tie(result, other_result) = foo();
which is just a bit more awkward. Guaranteed elision doesn't work here, however.
Going into stranger territory (and this is after out<>!),
We can use continuation passing style:
void foo( std::function<void(int result, int other_result)> );
and now callers do:
foo( [&](int result, int other_result) {
/* code */
} );
a benefit of this style is you can return an arbitrary number of values (with uniform type) without having to manage memory:
void get_all_values( std::function<void(int)> value )
the value callback could be called 500 times when you get_all_values( [&](int value){} ).
For pure insanity, you could even use a continuation on the continuation.
void foo( std::function<void(int, std::function<void(int)>)> result );
whose use looks like:
foo( [&](int result, auto&& other){ other([&](int other){
/* code */
}) });
which would permit many-one relationships between result and other.
Again with uniforn values, we can do this:
void foo( std::function< void(span<int>) > results )
here, we call the callback with a span of results. We can even do this repeatedly.
Using this, you can have a function that efficiently passes megabytes of data without doing any allocation off the stack.
void foo( std::function< void(span<int>) > results ) {
int local_buffer[1024];
std::size_t used = 0;
auto send_data=[&]{
if (!used) return;
results({ local_buffer, used });
used = 0;
};
auto add_datum=[&](int x){
local_buffer[used] = x;
++used;
if (used == 1024) send_data();
};
auto add_data=[&](gsl::span<int const> xs) {
for (auto x:xs) add_datum(x);
};
for (int i = 0; i < 7+(1<<20); ++i) {
add_datum(i);
}
send_data(); // any leftover
}
Now, std::function is a bit heavy for this, as we would be doing this in zero-overhead no-allocation environments. So we'd want a function_view that never allocates.
Another solution is:
std::function<void(std::function<void(int result, int other_result)>)> foo(int input);
where instead of taking the callback and invoking it, foo instead returns a function which takes the callback.
foo(7)([&](int result, int other_result){ /* code */ });
this breaks the output parameters from the input parameters by having separate brackets.
Use a Generator:
With variant and c++20 coroutines, you could make foo a generator of a variant of the return types (or just the return type). The syntax is not yet fixed, so I won't give examples.
Use signals/slot style:
In the world of signals and slots, a function that exposes a set of signals:
template<class...Args>
struct broadcaster;
broadcaster<int, int> foo();
allows you to create a foo that does work async and broadcasts the result when it is finished.
Use pipelines:
Down this line we have a variety of pipeline techniques, where a function doesn't do something but rather arranges for data to be connected in some way, and the doing is relatively independant.
foo( int_source )( int_dest1, int_dest2 );
then this code doesn't do anything until int_source has integers to provide it. When it does, int_dest1 and int_dest2 start recieving the results.
It's entirely dependent upon the actual function and the meaning of the multiple values, and their sizes:
If they're related as in your fraction example, then I'd go with a struct or class instance.
If they're not really related and can't be grouped into a class/struct then perhaps you should refactor your method into two.
Depending upon the in-memory size of the values you're returning, you may want to return a pointer to a class instance or struct, or use reference parameters.
With C++17 you can also return one ore more unmovable/uncopyable values (in certain cases). The possibility to return unmovable types come via the new guaranteed return value optimization, and it composes nicely with aggregates, and what can be called templated constructors.
template<typename T1,typename T2,typename T3>
struct many {
T1 a;
T2 b;
T3 c;
};
// guide:
template<class T1, class T2, class T3>
many(T1, T2, T3) -> many<T1, T2, T3>;
auto f(){ return many{string(),5.7, unmovable()}; };
int main(){
// in place construct x,y,z with a string, 5.7 and unmovable.
auto [x,y,z] = f();
}
The pretty thing about this is that it is guaranteed to not cause any copying or moving. You can make the example many struct variadic too. More details:
Returning variadic aggregates (struct) and syntax for C++17 variadic template 'construction deduction guide'
The OO solution for this is to create a ratio class. It wouldn't take any extra code (would save some), would be significantly cleaner/clearer, and would give you some extra refactorings letting you clean up code outside this class as well.
Actually I think someone recommended returning a structure, which is close enough but hides the intent that this needs to be a fully thought-out class with constructor and a few methods, in fact, the "method" that you originally mentioned (as returning the pair) should most likely be a member of this class returning an instance of itself.
I know your example was just an "Example", but the fact is that unless your function is doing way more than any function should be doing, if you want it to return multiple values you are almost certainly missing an object.
Don't be afraid to create these tiny classes to do little pieces of work--that's the magic of OO--you end up breaking it down until every method is very small and simple and every class small and understandable.
Another thing that should have been an indicator that something was wrong: in OO you have essentially no data--OO isn't about passing around data, a class needs to manage and manipulate it's own data internally, any data passing (including accessors) is a sign that you may need to rethink something..
There is precedent for returning structures in the C (and hence C++) standard with the div, ldiv (and, in C99, lldiv) functions from <stdlib.h> (or <cstdlib>).
The 'mix of return value and return parameters' is usually the least clean.
Having a function return a status and return data via return parameters is sensible in C; it is less obviously sensible in C++ where you could use exceptions to relay failure information instead.
If there are more than two return values, then a structure-like mechanism is probably best.
C++17, using std::make_tuple, structured binding and as much auto as possible:
#include <tuple>
#include <string>
#include <cstring>
auto func() {
// ...
return std::make_tuple(1, 2.2, std::string("str"), "cstr");
}
int main() {
auto [i, f, s, cs] = func();
return i + f + s.length() + strlen(cs);
}
With -O1 this optimizes out completely: https://godbolt.org/z/133rT9Pcq
-O3 needed only to optimize out std::string: https://godbolt.org/z/Mqbez73Kf
And here: https://godbolt.org/z/WWKvE3osv you can see GCC storing all the returned values packed together in a single chunk of memory (rdi+N), POD-style, proving there is no performance penalty.
Use a struct or a class for the return value. Using std::pair may work for now, but
it's inflexible if you decide later you want more info returned;
it's not very clear from the function's declaration in the header what is being returned and in what order.
Returning a structure with self-documenting member variable names will likely be less bug-prone for anyone using your function. Putting my coworker hat on for a moment, your divide_result structure is easy for me, a potential user of your function, to immediately understand after 2 seconds. Messing around with ouput parameters or mysterious pairs and tuples would take more time to read through and may be used incorrectly. And most likely even after using the function a few times I still won't remember the correct order of the arguments.
If your function returns a value via reference, the compiler cannot store it in a register when calling other functions because, theoretically, the first function can save the address of the variable passed to it in a globally accessible variable, and any subsecuently called functions may change it, so the compiler will have (1) save the value from registers back to memory before calling other functions and (2) re-read it when it is needed from the memory again after any of such calls.
If you return by reference, optimization of your program will suffer
Here, i am writing a program that is returning multiple values(more than two values) in c++. This program is executable in c++14 (G++4.9.2). program is like a calculator.
# include <tuple>
# include <iostream>
using namespace std;
tuple < int,int,int,int,int > cal(int n1, int n2)
{
return make_tuple(n1/n2,n1%n2,n1+n2,n1-n2,n1*n2);
}
int main()
{
int qut,rer,add,sub,mul,a,b;
cin>>a>>b;
tie(qut,rer,add,sub,mul)=cal(a,b);
cout << "quotient= "<<qut<<endl;
cout << "remainder= "<<rer<<endl;
cout << "addition= "<<add<<endl;
cout << "subtraction= "<<sub<<endl;
cout << "multiplication= "<<mul<<endl;
return 0;
}
So, you can clearly understand that in this way you can return multiple values from a function. using std::pair only 2 values can be returned while std::tuple can return more than two values.
I tend to use out-vals in functions like this, because I stick to the paradigm of a function returning success/error codes and I like to keep things uniform.
Alternatives include arrays, generators, and inversion of control, but none is appropriate here.
Some (e.g. Microsoft in historical Win32) tend to use reference parameters for simplicity, because it's clear who allocates and how it will look on the stack, reduces the proliferation of structures, and allows a separate return value for success.
"Pure" programmers prefer the struct, assuming it is the function value (as is the case here), rather than something that's touched incidentally by the function. If you had a more complicated procedure, or something with state, you'd probably use references (assuming you have a reason for not using a class).
I'd say there is no preferred method, it all depends on what you're going to do with the response. If the results are going to be used together in further processing then structures make sense, if not I'd tend to pass then as individual references unless the function was going to be used in a composite statement:
x = divide( x, y, z ) + divide( a, b, c );
I often choose to pass 'out structures' by reference in the parameter list rather than having the pass by copy overhead of returning a new structure (but this is sweating the small stuff).
void divide(int dividend, int divisor, Answer &ans)
Are out parameters confusing? A parameter sent as reference suggests the value is going to change (as opposed to a const reference). Sensible naming also removes confusion.
Why do you insist on a function with multiple return values? With OOP you can use a class offering a regular function with a single return value, and any number of additional "return values" like below. The advantage is that the caller has a choice of looking at the extra data members, but is not required to do this. This is the preferred method for complicated data base or networking calls, where lots of additional return info may be needed in case errors occur.
To answer your original question, this example has a method to return the quotient, which is what most callers may need, and additionally, after the method call, you can get the remainder as a data member.
class div{
public:
int remainder;
int quotient(int dividend, int divisor){
remainder = ...;
return ...;
}
};
Boost tuple would be my preferred choice for a generalized system of returning more than one value from a function.
Possible example:
include "boost/tuple/tuple.hpp"
tuple <int,int> divide( int dividend,int divisor )
{
return make_tuple(dividend / divisor,dividend % divisor )
}
rather than returning multiple values,just return one of them and make a reference of others in the required function for eg:
int divide(int a,int b,int quo,int &rem)
Here is the link to the "core guidelines" (by Bjarne Stroustrup and Herb Sutter) on this topic.
https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rf-out-multi
Partial Quote:
F.21: To return multiple “out” values, prefer returning a struct or tuple
Reason A return value is self-documenting as an “output-only” value. Note that C++ does have multiple return values, by convention of using a tuple (including pair), possibly with the extra convenience of tie or structured bindings (C++17) at the call site. Prefer using a named struct where there are semantics to the returned value. Otherwise, a nameless tuple is useful in generic code.
We can declare the function such that, it returns a structure type user defined variable or a pointer to it . And by the property of a structure, we know that a structure in C can hold multiple values of asymmetrical types (i.e. one int variable, four char variables, two float variables and so on…)
I would just do it by reference if it's only a few return values but for more complex types you can also just do it like this :
static struct SomeReturnType {int a,b,c; string str;} SomeFunction()
{
return {1,2,3,string("hello world")}; // make sure you return values in the right order!
}
use "static" to limit the scope of the return type to this compilation unit if it's only meant to be a temporary return type.
SomeReturnType st = SomeFunction();
cout << "a " << st.a << endl;
cout << "b " << st.b << endl;
cout << "c " << st.c << endl;
cout << "str " << st.str << endl;
This is definitely not the prettiest way to do it but it will work.
Quick answer:
#include <iostream>
using namespace std;
// different values of [operate] can return different number.
int yourFunction(int a, int b, int operate)
{
a = 1;
b = 2;
if (operate== 1)
{
return a;
}
else
{
return b;
}
}
int main()
{
int a, b;
a = yourFunction(a, b, 1); // get return 1
b = yourFunction(a, b, 2); // get return 2
return 0;
}
Is there a preferred way to return multiple values from a C++ function? For example, imagine a function that divides two integers and returns both the quotient and the remainder. One way I commonly see is to use reference parameters:
void divide(int dividend, int divisor, int& quotient, int& remainder);
A variation is to return one value and pass the other through a reference parameter:
int divide(int dividend, int divisor, int& remainder);
Another way would be to declare a struct to contain all of the results and return that:
struct divide_result {
int quotient;
int remainder;
};
divide_result divide(int dividend, int divisor);
Is one of these ways generally preferred, or are there other suggestions?
Edit: In the real-world code, there may be more than two results. They may also be of different types.
In C++11 you can:
#include <tuple>
std::tuple<int, int> divide(int dividend, int divisor) {
return std::make_tuple(dividend / divisor, dividend % divisor);
}
#include <iostream>
int main() {
using namespace std;
int quotient, remainder;
tie(quotient, remainder) = divide(14, 3);
cout << quotient << ',' << remainder << endl;
}
In C++17:
#include <tuple>
std::tuple<int, int> divide(int dividend, int divisor) {
return {dividend / divisor, dividend % divisor};
}
#include <iostream>
int main() {
using namespace std;
auto [quotient, remainder] = divide(14, 3);
cout << quotient << ',' << remainder << endl;
}
or with structs:
auto divide(int dividend, int divisor) {
struct result {int quotient; int remainder;};
return result {dividend / divisor, dividend % divisor};
}
#include <iostream>
int main() {
using namespace std;
auto result = divide(14, 3);
cout << result.quotient << ',' << result.remainder << endl;
// or
auto [quotient, remainder] = divide(14, 3);
cout << quotient << ',' << remainder << endl;
}
For returning two values I use a std::pair (usually typedef'd). You should look at boost::tuple (in C++11 and newer, there's std::tuple) for more than two return results.
With introduction of structured binding in C++ 17, returning std::tuple should probably become accepted standard.
Personally, I generally dislike return parameters for a number of reasons:
it is not always obvious in the invocation which parameters are ins and which are outs
you generally have to create a local variable to catch the result, while return values can be used inline (which may or may not be a good idea, but at least you have the option)
it seems cleaner to me to have an "in door" and an "out door" to a function -- all the inputs go in here, all the outputs come out there
I like to keep my argument lists as short as possible
I also have some reservations about the pair/tuple technique. Mainly, there is often no natural order to the return values. How is the reader of the code to know whether result.first is the quotient or the remainder? And the implementer could change the order, which would break existing code. This is especially insidious if the values are the same type so that no compiler error or warning would be generated. Actually, these arguments apply to return parameters as well.
Here's another code example, this one a bit less trivial:
pair<double,double> calculateResultingVelocity(double windSpeed, double windAzimuth,
double planeAirspeed, double planeCourse);
pair<double,double> result = calculateResultingVelocity(25, 320, 280, 90);
cout << result.first << endl;
cout << result.second << endl;
Does this print groundspeed and course, or course and groundspeed? It's not obvious.
Compare to this:
struct Velocity {
double speed;
double azimuth;
};
Velocity calculateResultingVelocity(double windSpeed, double windAzimuth,
double planeAirspeed, double planeCourse);
Velocity result = calculateResultingVelocity(25, 320, 280, 90);
cout << result.speed << endl;
cout << result.azimuth << endl;
I think this is clearer.
So I think my first choice, in general, is the struct technique. The pair/tuple idea is likely a great solution in certain cases. I'd like to avoid the return parameters when possible.
std::pair<int, int> divide(int dividend, int divisor)
{
// :
return std::make_pair(quotient, remainder);
}
std::pair<int, int> answer = divide(5,2);
// answer.first == quotient
// answer.second == remainder
std::pair is essentially your struct solution, but already defined for you, and ready to adapt to any two data types.
There are a bunch of ways to return multiple parameters. I'm going to be exhastive.
Use reference parameters:
void foo( int& result, int& other_result );
Use pointer parameters:
void foo( int* result, int* other_result );
which has the advantage that you have to do a & at the call-site, possibly alerting people it is an out-parameter.
Write an out<?> template and use it:
template<class T>
struct out {
std::function<void(T)> target;
out(T* t):target([t](T&& in){ if (t) *t = std::move(in); }) {}
out(std::optional<T>* t):target([t](T&& in){ if (t) t->emplace(std::move(in)); }) {}
out(std::aligned_storage_t<sizeof(T), alignof(T)>* t):
target([t](T&& in){ ::new( (void*)t ) T(std::move(in)); } ) {}
template<class...Args> // TODO: SFINAE enable_if test
void emplace(Args&&...args) {
target( T(std::forward<Args>(args)...) );
}
template<class X> // TODO: SFINAE enable_if test
void operator=(X&&x){ emplace(std::forward<X>(x)); }
template<class...Args> // TODO: SFINAE enable_if test
void operator()(Args...&&args){ emplace(std::forward<Args>(args)...); }
};
then we can do:
void foo( out<int> result, out<int> other_result )
and all is good. foo is no longer able to read any value passed in as a bonus.
Other ways of defining a spot you can put data can be used to construct out. A callback to emplace things somewhere, for example.
We can return a structure:
struct foo_r { int result; int other_result; };
foo_r foo();
whick works ok in every version of C++, and in c++17 this also permits:
auto&&[result, other_result]=foo();
at zero cost. Parameters can even not even be moved thanks to guaranteed elision.
We could return a std::tuple:
std::tuple<int, int> foo();
which has the downside that parameters are not named. This permits the c++17:
auto&&[result, other_result]=foo();
as well. Prior to c++17 we can instead do:
int result, other_result;
std::tie(result, other_result) = foo();
which is just a bit more awkward. Guaranteed elision doesn't work here, however.
Going into stranger territory (and this is after out<>!),
We can use continuation passing style:
void foo( std::function<void(int result, int other_result)> );
and now callers do:
foo( [&](int result, int other_result) {
/* code */
} );
a benefit of this style is you can return an arbitrary number of values (with uniform type) without having to manage memory:
void get_all_values( std::function<void(int)> value )
the value callback could be called 500 times when you get_all_values( [&](int value){} ).
For pure insanity, you could even use a continuation on the continuation.
void foo( std::function<void(int, std::function<void(int)>)> result );
whose use looks like:
foo( [&](int result, auto&& other){ other([&](int other){
/* code */
}) });
which would permit many-one relationships between result and other.
Again with uniforn values, we can do this:
void foo( std::function< void(span<int>) > results )
here, we call the callback with a span of results. We can even do this repeatedly.
Using this, you can have a function that efficiently passes megabytes of data without doing any allocation off the stack.
void foo( std::function< void(span<int>) > results ) {
int local_buffer[1024];
std::size_t used = 0;
auto send_data=[&]{
if (!used) return;
results({ local_buffer, used });
used = 0;
};
auto add_datum=[&](int x){
local_buffer[used] = x;
++used;
if (used == 1024) send_data();
};
auto add_data=[&](gsl::span<int const> xs) {
for (auto x:xs) add_datum(x);
};
for (int i = 0; i < 7+(1<<20); ++i) {
add_datum(i);
}
send_data(); // any leftover
}
Now, std::function is a bit heavy for this, as we would be doing this in zero-overhead no-allocation environments. So we'd want a function_view that never allocates.
Another solution is:
std::function<void(std::function<void(int result, int other_result)>)> foo(int input);
where instead of taking the callback and invoking it, foo instead returns a function which takes the callback.
foo(7)([&](int result, int other_result){ /* code */ });
this breaks the output parameters from the input parameters by having separate brackets.
Use a Generator:
With variant and c++20 coroutines, you could make foo a generator of a variant of the return types (or just the return type). The syntax is not yet fixed, so I won't give examples.
Use signals/slot style:
In the world of signals and slots, a function that exposes a set of signals:
template<class...Args>
struct broadcaster;
broadcaster<int, int> foo();
allows you to create a foo that does work async and broadcasts the result when it is finished.
Use pipelines:
Down this line we have a variety of pipeline techniques, where a function doesn't do something but rather arranges for data to be connected in some way, and the doing is relatively independant.
foo( int_source )( int_dest1, int_dest2 );
then this code doesn't do anything until int_source has integers to provide it. When it does, int_dest1 and int_dest2 start recieving the results.
It's entirely dependent upon the actual function and the meaning of the multiple values, and their sizes:
If they're related as in your fraction example, then I'd go with a struct or class instance.
If they're not really related and can't be grouped into a class/struct then perhaps you should refactor your method into two.
Depending upon the in-memory size of the values you're returning, you may want to return a pointer to a class instance or struct, or use reference parameters.
With C++17 you can also return one ore more unmovable/uncopyable values (in certain cases). The possibility to return unmovable types come via the new guaranteed return value optimization, and it composes nicely with aggregates, and what can be called templated constructors.
template<typename T1,typename T2,typename T3>
struct many {
T1 a;
T2 b;
T3 c;
};
// guide:
template<class T1, class T2, class T3>
many(T1, T2, T3) -> many<T1, T2, T3>;
auto f(){ return many{string(),5.7, unmovable()}; };
int main(){
// in place construct x,y,z with a string, 5.7 and unmovable.
auto [x,y,z] = f();
}
The pretty thing about this is that it is guaranteed to not cause any copying or moving. You can make the example many struct variadic too. More details:
Returning variadic aggregates (struct) and syntax for C++17 variadic template 'construction deduction guide'
The OO solution for this is to create a ratio class. It wouldn't take any extra code (would save some), would be significantly cleaner/clearer, and would give you some extra refactorings letting you clean up code outside this class as well.
Actually I think someone recommended returning a structure, which is close enough but hides the intent that this needs to be a fully thought-out class with constructor and a few methods, in fact, the "method" that you originally mentioned (as returning the pair) should most likely be a member of this class returning an instance of itself.
I know your example was just an "Example", but the fact is that unless your function is doing way more than any function should be doing, if you want it to return multiple values you are almost certainly missing an object.
Don't be afraid to create these tiny classes to do little pieces of work--that's the magic of OO--you end up breaking it down until every method is very small and simple and every class small and understandable.
Another thing that should have been an indicator that something was wrong: in OO you have essentially no data--OO isn't about passing around data, a class needs to manage and manipulate it's own data internally, any data passing (including accessors) is a sign that you may need to rethink something..
There is precedent for returning structures in the C (and hence C++) standard with the div, ldiv (and, in C99, lldiv) functions from <stdlib.h> (or <cstdlib>).
The 'mix of return value and return parameters' is usually the least clean.
Having a function return a status and return data via return parameters is sensible in C; it is less obviously sensible in C++ where you could use exceptions to relay failure information instead.
If there are more than two return values, then a structure-like mechanism is probably best.
C++17, using std::make_tuple, structured binding and as much auto as possible:
#include <tuple>
#include <string>
#include <cstring>
auto func() {
// ...
return std::make_tuple(1, 2.2, std::string("str"), "cstr");
}
int main() {
auto [i, f, s, cs] = func();
return i + f + s.length() + strlen(cs);
}
With -O1 this optimizes out completely: https://godbolt.org/z/133rT9Pcq
-O3 needed only to optimize out std::string: https://godbolt.org/z/Mqbez73Kf
And here: https://godbolt.org/z/WWKvE3osv you can see GCC storing all the returned values packed together in a single chunk of memory (rdi+N), POD-style, proving there is no performance penalty.
Use a struct or a class for the return value. Using std::pair may work for now, but
it's inflexible if you decide later you want more info returned;
it's not very clear from the function's declaration in the header what is being returned and in what order.
Returning a structure with self-documenting member variable names will likely be less bug-prone for anyone using your function. Putting my coworker hat on for a moment, your divide_result structure is easy for me, a potential user of your function, to immediately understand after 2 seconds. Messing around with ouput parameters or mysterious pairs and tuples would take more time to read through and may be used incorrectly. And most likely even after using the function a few times I still won't remember the correct order of the arguments.
If your function returns a value via reference, the compiler cannot store it in a register when calling other functions because, theoretically, the first function can save the address of the variable passed to it in a globally accessible variable, and any subsecuently called functions may change it, so the compiler will have (1) save the value from registers back to memory before calling other functions and (2) re-read it when it is needed from the memory again after any of such calls.
If you return by reference, optimization of your program will suffer
Here, i am writing a program that is returning multiple values(more than two values) in c++. This program is executable in c++14 (G++4.9.2). program is like a calculator.
# include <tuple>
# include <iostream>
using namespace std;
tuple < int,int,int,int,int > cal(int n1, int n2)
{
return make_tuple(n1/n2,n1%n2,n1+n2,n1-n2,n1*n2);
}
int main()
{
int qut,rer,add,sub,mul,a,b;
cin>>a>>b;
tie(qut,rer,add,sub,mul)=cal(a,b);
cout << "quotient= "<<qut<<endl;
cout << "remainder= "<<rer<<endl;
cout << "addition= "<<add<<endl;
cout << "subtraction= "<<sub<<endl;
cout << "multiplication= "<<mul<<endl;
return 0;
}
So, you can clearly understand that in this way you can return multiple values from a function. using std::pair only 2 values can be returned while std::tuple can return more than two values.
I tend to use out-vals in functions like this, because I stick to the paradigm of a function returning success/error codes and I like to keep things uniform.
Alternatives include arrays, generators, and inversion of control, but none is appropriate here.
Some (e.g. Microsoft in historical Win32) tend to use reference parameters for simplicity, because it's clear who allocates and how it will look on the stack, reduces the proliferation of structures, and allows a separate return value for success.
"Pure" programmers prefer the struct, assuming it is the function value (as is the case here), rather than something that's touched incidentally by the function. If you had a more complicated procedure, or something with state, you'd probably use references (assuming you have a reason for not using a class).
I'd say there is no preferred method, it all depends on what you're going to do with the response. If the results are going to be used together in further processing then structures make sense, if not I'd tend to pass then as individual references unless the function was going to be used in a composite statement:
x = divide( x, y, z ) + divide( a, b, c );
I often choose to pass 'out structures' by reference in the parameter list rather than having the pass by copy overhead of returning a new structure (but this is sweating the small stuff).
void divide(int dividend, int divisor, Answer &ans)
Are out parameters confusing? A parameter sent as reference suggests the value is going to change (as opposed to a const reference). Sensible naming also removes confusion.
Why do you insist on a function with multiple return values? With OOP you can use a class offering a regular function with a single return value, and any number of additional "return values" like below. The advantage is that the caller has a choice of looking at the extra data members, but is not required to do this. This is the preferred method for complicated data base or networking calls, where lots of additional return info may be needed in case errors occur.
To answer your original question, this example has a method to return the quotient, which is what most callers may need, and additionally, after the method call, you can get the remainder as a data member.
class div{
public:
int remainder;
int quotient(int dividend, int divisor){
remainder = ...;
return ...;
}
};
Boost tuple would be my preferred choice for a generalized system of returning more than one value from a function.
Possible example:
include "boost/tuple/tuple.hpp"
tuple <int,int> divide( int dividend,int divisor )
{
return make_tuple(dividend / divisor,dividend % divisor )
}
rather than returning multiple values,just return one of them and make a reference of others in the required function for eg:
int divide(int a,int b,int quo,int &rem)
Here is the link to the "core guidelines" (by Bjarne Stroustrup and Herb Sutter) on this topic.
https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rf-out-multi
Partial Quote:
F.21: To return multiple “out” values, prefer returning a struct or tuple
Reason A return value is self-documenting as an “output-only” value. Note that C++ does have multiple return values, by convention of using a tuple (including pair), possibly with the extra convenience of tie or structured bindings (C++17) at the call site. Prefer using a named struct where there are semantics to the returned value. Otherwise, a nameless tuple is useful in generic code.
We can declare the function such that, it returns a structure type user defined variable or a pointer to it . And by the property of a structure, we know that a structure in C can hold multiple values of asymmetrical types (i.e. one int variable, four char variables, two float variables and so on…)
I would just do it by reference if it's only a few return values but for more complex types you can also just do it like this :
static struct SomeReturnType {int a,b,c; string str;} SomeFunction()
{
return {1,2,3,string("hello world")}; // make sure you return values in the right order!
}
use "static" to limit the scope of the return type to this compilation unit if it's only meant to be a temporary return type.
SomeReturnType st = SomeFunction();
cout << "a " << st.a << endl;
cout << "b " << st.b << endl;
cout << "c " << st.c << endl;
cout << "str " << st.str << endl;
This is definitely not the prettiest way to do it but it will work.
Quick answer:
#include <iostream>
using namespace std;
// different values of [operate] can return different number.
int yourFunction(int a, int b, int operate)
{
a = 1;
b = 2;
if (operate== 1)
{
return a;
}
else
{
return b;
}
}
int main()
{
int a, b;
a = yourFunction(a, b, 1); // get return 1
b = yourFunction(a, b, 2); // get return 2
return 0;
}
Is there a preferred way to return multiple values from a C++ function? For example, imagine a function that divides two integers and returns both the quotient and the remainder. One way I commonly see is to use reference parameters:
void divide(int dividend, int divisor, int& quotient, int& remainder);
A variation is to return one value and pass the other through a reference parameter:
int divide(int dividend, int divisor, int& remainder);
Another way would be to declare a struct to contain all of the results and return that:
struct divide_result {
int quotient;
int remainder;
};
divide_result divide(int dividend, int divisor);
Is one of these ways generally preferred, or are there other suggestions?
Edit: In the real-world code, there may be more than two results. They may also be of different types.
In C++11 you can:
#include <tuple>
std::tuple<int, int> divide(int dividend, int divisor) {
return std::make_tuple(dividend / divisor, dividend % divisor);
}
#include <iostream>
int main() {
using namespace std;
int quotient, remainder;
tie(quotient, remainder) = divide(14, 3);
cout << quotient << ',' << remainder << endl;
}
In C++17:
#include <tuple>
std::tuple<int, int> divide(int dividend, int divisor) {
return {dividend / divisor, dividend % divisor};
}
#include <iostream>
int main() {
using namespace std;
auto [quotient, remainder] = divide(14, 3);
cout << quotient << ',' << remainder << endl;
}
or with structs:
auto divide(int dividend, int divisor) {
struct result {int quotient; int remainder;};
return result {dividend / divisor, dividend % divisor};
}
#include <iostream>
int main() {
using namespace std;
auto result = divide(14, 3);
cout << result.quotient << ',' << result.remainder << endl;
// or
auto [quotient, remainder] = divide(14, 3);
cout << quotient << ',' << remainder << endl;
}
For returning two values I use a std::pair (usually typedef'd). You should look at boost::tuple (in C++11 and newer, there's std::tuple) for more than two return results.
With introduction of structured binding in C++ 17, returning std::tuple should probably become accepted standard.
Personally, I generally dislike return parameters for a number of reasons:
it is not always obvious in the invocation which parameters are ins and which are outs
you generally have to create a local variable to catch the result, while return values can be used inline (which may or may not be a good idea, but at least you have the option)
it seems cleaner to me to have an "in door" and an "out door" to a function -- all the inputs go in here, all the outputs come out there
I like to keep my argument lists as short as possible
I also have some reservations about the pair/tuple technique. Mainly, there is often no natural order to the return values. How is the reader of the code to know whether result.first is the quotient or the remainder? And the implementer could change the order, which would break existing code. This is especially insidious if the values are the same type so that no compiler error or warning would be generated. Actually, these arguments apply to return parameters as well.
Here's another code example, this one a bit less trivial:
pair<double,double> calculateResultingVelocity(double windSpeed, double windAzimuth,
double planeAirspeed, double planeCourse);
pair<double,double> result = calculateResultingVelocity(25, 320, 280, 90);
cout << result.first << endl;
cout << result.second << endl;
Does this print groundspeed and course, or course and groundspeed? It's not obvious.
Compare to this:
struct Velocity {
double speed;
double azimuth;
};
Velocity calculateResultingVelocity(double windSpeed, double windAzimuth,
double planeAirspeed, double planeCourse);
Velocity result = calculateResultingVelocity(25, 320, 280, 90);
cout << result.speed << endl;
cout << result.azimuth << endl;
I think this is clearer.
So I think my first choice, in general, is the struct technique. The pair/tuple idea is likely a great solution in certain cases. I'd like to avoid the return parameters when possible.
std::pair<int, int> divide(int dividend, int divisor)
{
// :
return std::make_pair(quotient, remainder);
}
std::pair<int, int> answer = divide(5,2);
// answer.first == quotient
// answer.second == remainder
std::pair is essentially your struct solution, but already defined for you, and ready to adapt to any two data types.
There are a bunch of ways to return multiple parameters. I'm going to be exhastive.
Use reference parameters:
void foo( int& result, int& other_result );
Use pointer parameters:
void foo( int* result, int* other_result );
which has the advantage that you have to do a & at the call-site, possibly alerting people it is an out-parameter.
Write an out<?> template and use it:
template<class T>
struct out {
std::function<void(T)> target;
out(T* t):target([t](T&& in){ if (t) *t = std::move(in); }) {}
out(std::optional<T>* t):target([t](T&& in){ if (t) t->emplace(std::move(in)); }) {}
out(std::aligned_storage_t<sizeof(T), alignof(T)>* t):
target([t](T&& in){ ::new( (void*)t ) T(std::move(in)); } ) {}
template<class...Args> // TODO: SFINAE enable_if test
void emplace(Args&&...args) {
target( T(std::forward<Args>(args)...) );
}
template<class X> // TODO: SFINAE enable_if test
void operator=(X&&x){ emplace(std::forward<X>(x)); }
template<class...Args> // TODO: SFINAE enable_if test
void operator()(Args...&&args){ emplace(std::forward<Args>(args)...); }
};
then we can do:
void foo( out<int> result, out<int> other_result )
and all is good. foo is no longer able to read any value passed in as a bonus.
Other ways of defining a spot you can put data can be used to construct out. A callback to emplace things somewhere, for example.
We can return a structure:
struct foo_r { int result; int other_result; };
foo_r foo();
whick works ok in every version of C++, and in c++17 this also permits:
auto&&[result, other_result]=foo();
at zero cost. Parameters can even not even be moved thanks to guaranteed elision.
We could return a std::tuple:
std::tuple<int, int> foo();
which has the downside that parameters are not named. This permits the c++17:
auto&&[result, other_result]=foo();
as well. Prior to c++17 we can instead do:
int result, other_result;
std::tie(result, other_result) = foo();
which is just a bit more awkward. Guaranteed elision doesn't work here, however.
Going into stranger territory (and this is after out<>!),
We can use continuation passing style:
void foo( std::function<void(int result, int other_result)> );
and now callers do:
foo( [&](int result, int other_result) {
/* code */
} );
a benefit of this style is you can return an arbitrary number of values (with uniform type) without having to manage memory:
void get_all_values( std::function<void(int)> value )
the value callback could be called 500 times when you get_all_values( [&](int value){} ).
For pure insanity, you could even use a continuation on the continuation.
void foo( std::function<void(int, std::function<void(int)>)> result );
whose use looks like:
foo( [&](int result, auto&& other){ other([&](int other){
/* code */
}) });
which would permit many-one relationships between result and other.
Again with uniforn values, we can do this:
void foo( std::function< void(span<int>) > results )
here, we call the callback with a span of results. We can even do this repeatedly.
Using this, you can have a function that efficiently passes megabytes of data without doing any allocation off the stack.
void foo( std::function< void(span<int>) > results ) {
int local_buffer[1024];
std::size_t used = 0;
auto send_data=[&]{
if (!used) return;
results({ local_buffer, used });
used = 0;
};
auto add_datum=[&](int x){
local_buffer[used] = x;
++used;
if (used == 1024) send_data();
};
auto add_data=[&](gsl::span<int const> xs) {
for (auto x:xs) add_datum(x);
};
for (int i = 0; i < 7+(1<<20); ++i) {
add_datum(i);
}
send_data(); // any leftover
}
Now, std::function is a bit heavy for this, as we would be doing this in zero-overhead no-allocation environments. So we'd want a function_view that never allocates.
Another solution is:
std::function<void(std::function<void(int result, int other_result)>)> foo(int input);
where instead of taking the callback and invoking it, foo instead returns a function which takes the callback.
foo(7)([&](int result, int other_result){ /* code */ });
this breaks the output parameters from the input parameters by having separate brackets.
Use a Generator:
With variant and c++20 coroutines, you could make foo a generator of a variant of the return types (or just the return type). The syntax is not yet fixed, so I won't give examples.
Use signals/slot style:
In the world of signals and slots, a function that exposes a set of signals:
template<class...Args>
struct broadcaster;
broadcaster<int, int> foo();
allows you to create a foo that does work async and broadcasts the result when it is finished.
Use pipelines:
Down this line we have a variety of pipeline techniques, where a function doesn't do something but rather arranges for data to be connected in some way, and the doing is relatively independant.
foo( int_source )( int_dest1, int_dest2 );
then this code doesn't do anything until int_source has integers to provide it. When it does, int_dest1 and int_dest2 start recieving the results.
It's entirely dependent upon the actual function and the meaning of the multiple values, and their sizes:
If they're related as in your fraction example, then I'd go with a struct or class instance.
If they're not really related and can't be grouped into a class/struct then perhaps you should refactor your method into two.
Depending upon the in-memory size of the values you're returning, you may want to return a pointer to a class instance or struct, or use reference parameters.
With C++17 you can also return one ore more unmovable/uncopyable values (in certain cases). The possibility to return unmovable types come via the new guaranteed return value optimization, and it composes nicely with aggregates, and what can be called templated constructors.
template<typename T1,typename T2,typename T3>
struct many {
T1 a;
T2 b;
T3 c;
};
// guide:
template<class T1, class T2, class T3>
many(T1, T2, T3) -> many<T1, T2, T3>;
auto f(){ return many{string(),5.7, unmovable()}; };
int main(){
// in place construct x,y,z with a string, 5.7 and unmovable.
auto [x,y,z] = f();
}
The pretty thing about this is that it is guaranteed to not cause any copying or moving. You can make the example many struct variadic too. More details:
Returning variadic aggregates (struct) and syntax for C++17 variadic template 'construction deduction guide'
The OO solution for this is to create a ratio class. It wouldn't take any extra code (would save some), would be significantly cleaner/clearer, and would give you some extra refactorings letting you clean up code outside this class as well.
Actually I think someone recommended returning a structure, which is close enough but hides the intent that this needs to be a fully thought-out class with constructor and a few methods, in fact, the "method" that you originally mentioned (as returning the pair) should most likely be a member of this class returning an instance of itself.
I know your example was just an "Example", but the fact is that unless your function is doing way more than any function should be doing, if you want it to return multiple values you are almost certainly missing an object.
Don't be afraid to create these tiny classes to do little pieces of work--that's the magic of OO--you end up breaking it down until every method is very small and simple and every class small and understandable.
Another thing that should have been an indicator that something was wrong: in OO you have essentially no data--OO isn't about passing around data, a class needs to manage and manipulate it's own data internally, any data passing (including accessors) is a sign that you may need to rethink something..
There is precedent for returning structures in the C (and hence C++) standard with the div, ldiv (and, in C99, lldiv) functions from <stdlib.h> (or <cstdlib>).
The 'mix of return value and return parameters' is usually the least clean.
Having a function return a status and return data via return parameters is sensible in C; it is less obviously sensible in C++ where you could use exceptions to relay failure information instead.
If there are more than two return values, then a structure-like mechanism is probably best.
C++17, using std::make_tuple, structured binding and as much auto as possible:
#include <tuple>
#include <string>
#include <cstring>
auto func() {
// ...
return std::make_tuple(1, 2.2, std::string("str"), "cstr");
}
int main() {
auto [i, f, s, cs] = func();
return i + f + s.length() + strlen(cs);
}
With -O1 this optimizes out completely: https://godbolt.org/z/133rT9Pcq
-O3 needed only to optimize out std::string: https://godbolt.org/z/Mqbez73Kf
And here: https://godbolt.org/z/WWKvE3osv you can see GCC storing all the returned values packed together in a single chunk of memory (rdi+N), POD-style, proving there is no performance penalty.
Use a struct or a class for the return value. Using std::pair may work for now, but
it's inflexible if you decide later you want more info returned;
it's not very clear from the function's declaration in the header what is being returned and in what order.
Returning a structure with self-documenting member variable names will likely be less bug-prone for anyone using your function. Putting my coworker hat on for a moment, your divide_result structure is easy for me, a potential user of your function, to immediately understand after 2 seconds. Messing around with ouput parameters or mysterious pairs and tuples would take more time to read through and may be used incorrectly. And most likely even after using the function a few times I still won't remember the correct order of the arguments.
If your function returns a value via reference, the compiler cannot store it in a register when calling other functions because, theoretically, the first function can save the address of the variable passed to it in a globally accessible variable, and any subsecuently called functions may change it, so the compiler will have (1) save the value from registers back to memory before calling other functions and (2) re-read it when it is needed from the memory again after any of such calls.
If you return by reference, optimization of your program will suffer
Here, i am writing a program that is returning multiple values(more than two values) in c++. This program is executable in c++14 (G++4.9.2). program is like a calculator.
# include <tuple>
# include <iostream>
using namespace std;
tuple < int,int,int,int,int > cal(int n1, int n2)
{
return make_tuple(n1/n2,n1%n2,n1+n2,n1-n2,n1*n2);
}
int main()
{
int qut,rer,add,sub,mul,a,b;
cin>>a>>b;
tie(qut,rer,add,sub,mul)=cal(a,b);
cout << "quotient= "<<qut<<endl;
cout << "remainder= "<<rer<<endl;
cout << "addition= "<<add<<endl;
cout << "subtraction= "<<sub<<endl;
cout << "multiplication= "<<mul<<endl;
return 0;
}
So, you can clearly understand that in this way you can return multiple values from a function. using std::pair only 2 values can be returned while std::tuple can return more than two values.
I tend to use out-vals in functions like this, because I stick to the paradigm of a function returning success/error codes and I like to keep things uniform.
Alternatives include arrays, generators, and inversion of control, but none is appropriate here.
Some (e.g. Microsoft in historical Win32) tend to use reference parameters for simplicity, because it's clear who allocates and how it will look on the stack, reduces the proliferation of structures, and allows a separate return value for success.
"Pure" programmers prefer the struct, assuming it is the function value (as is the case here), rather than something that's touched incidentally by the function. If you had a more complicated procedure, or something with state, you'd probably use references (assuming you have a reason for not using a class).
I'd say there is no preferred method, it all depends on what you're going to do with the response. If the results are going to be used together in further processing then structures make sense, if not I'd tend to pass then as individual references unless the function was going to be used in a composite statement:
x = divide( x, y, z ) + divide( a, b, c );
I often choose to pass 'out structures' by reference in the parameter list rather than having the pass by copy overhead of returning a new structure (but this is sweating the small stuff).
void divide(int dividend, int divisor, Answer &ans)
Are out parameters confusing? A parameter sent as reference suggests the value is going to change (as opposed to a const reference). Sensible naming also removes confusion.
Why do you insist on a function with multiple return values? With OOP you can use a class offering a regular function with a single return value, and any number of additional "return values" like below. The advantage is that the caller has a choice of looking at the extra data members, but is not required to do this. This is the preferred method for complicated data base or networking calls, where lots of additional return info may be needed in case errors occur.
To answer your original question, this example has a method to return the quotient, which is what most callers may need, and additionally, after the method call, you can get the remainder as a data member.
class div{
public:
int remainder;
int quotient(int dividend, int divisor){
remainder = ...;
return ...;
}
};
Boost tuple would be my preferred choice for a generalized system of returning more than one value from a function.
Possible example:
include "boost/tuple/tuple.hpp"
tuple <int,int> divide( int dividend,int divisor )
{
return make_tuple(dividend / divisor,dividend % divisor )
}
rather than returning multiple values,just return one of them and make a reference of others in the required function for eg:
int divide(int a,int b,int quo,int &rem)
Here is the link to the "core guidelines" (by Bjarne Stroustrup and Herb Sutter) on this topic.
https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rf-out-multi
Partial Quote:
F.21: To return multiple “out” values, prefer returning a struct or tuple
Reason A return value is self-documenting as an “output-only” value. Note that C++ does have multiple return values, by convention of using a tuple (including pair), possibly with the extra convenience of tie or structured bindings (C++17) at the call site. Prefer using a named struct where there are semantics to the returned value. Otherwise, a nameless tuple is useful in generic code.
We can declare the function such that, it returns a structure type user defined variable or a pointer to it . And by the property of a structure, we know that a structure in C can hold multiple values of asymmetrical types (i.e. one int variable, four char variables, two float variables and so on…)
I would just do it by reference if it's only a few return values but for more complex types you can also just do it like this :
static struct SomeReturnType {int a,b,c; string str;} SomeFunction()
{
return {1,2,3,string("hello world")}; // make sure you return values in the right order!
}
use "static" to limit the scope of the return type to this compilation unit if it's only meant to be a temporary return type.
SomeReturnType st = SomeFunction();
cout << "a " << st.a << endl;
cout << "b " << st.b << endl;
cout << "c " << st.c << endl;
cout << "str " << st.str << endl;
This is definitely not the prettiest way to do it but it will work.
Quick answer:
#include <iostream>
using namespace std;
// different values of [operate] can return different number.
int yourFunction(int a, int b, int operate)
{
a = 1;
b = 2;
if (operate== 1)
{
return a;
}
else
{
return b;
}
}
int main()
{
int a, b;
a = yourFunction(a, b, 1); // get return 1
b = yourFunction(a, b, 2); // get return 2
return 0;
}
I have two arrays comprising x,y vales for y=f(x). I would like to provide a function that finds the value of x that corresponds to either the min or max sampled value of y.
What is an efficient way to select proper comparison operator before looping over the values in the arrays?
For example, I would like to do something like the following:
double FindExtremum(const double* x, const double* y,
const unsigned int n, const bool isMin) {
static std::less<double> lt;
static std::greater<double> gt;
std::binary_function<double,double,bool>& IsBeyond = isMin ? lt : gt;
double xm(*x), ym(*y);
for (unsigned int i=0; i<n; ++i, ++x, ++y) {
if (IsBeyond()(*y,ym)) {
ym = *y;
xm = *x;
}
}
}
Unfortunately, the base class std::binary_function does not define a virtual operator().
Will a compiler like g++ 4.8 be able to optimize the most straight forward implementation?
double FindExtremum(const double* x, const double* y,
const unsigned int n, const bool isMin) {
double xm(*x), ym(*y);
for (unsigned int i=0; i<n; ++i, ++x, ++y) {
if ( ( isMin && (*y<ym)) ||
(!isMin && (*y>ym)) ) {
ym = *y;
xm = *x;
}
}
}
Is there another way to arrange things to make it easy for the compiler to optimize? Is there a well known algorithm for doing this?
I would prefer to avoid using a templated function, if possible.
You would need to pass the comparison functor as a templated function parameter, e.g.
template <typename Compare>
double FindExtremum(const double* x, const double* y,
const unsigned int n, Compare compare) {
double xm(*x), ym(*y);
for (unsigned int i=0; i<n; ++i, ++x, ++y) {
if (compare(*y,ym)) {
ym = *y;
xm = *x;
}
}
}
Then if you need runtime choice, write something like this:
if (isMin) {
FindExtremum(x, y, n, std::less<double>());
} else {
FindExtremum(x, y, n, std::greater<double>());
}
Avoiding a templated function is not really possible in this case. The best performing code will be one that embeds the comparison operation directly in the loop, avoiding a function call - you can either write a template or write two copies of this function. A templated function is clearly the better solution.
For ultimate efficiency, make the comparison operator or the comparison operator choice a template parameter, and don't forget to measure.
When striving for utmost micro-efficiency, doing virtual calls is not in the direction of the goal.
That said, this is most likely a case of premature optimization, which Donald Knuth described thusly:
“Premature optimization is the root of all evil”
(I omitted his reservations, it sounds more forceful that way. :-) )
Instead of engaging in micro-optimization frenzy, which gains you little if anything, and wastes your time, I recommend more productively trying to make the code as clear and provably correct as possible. For example, use std::vector instead of raw arrays and separately passed sizes. And, for example, don't call the boolean comparison operator compare, as recommended in another answer, since that's the conventional name for tri-valued compare (e.g. as in std::string::compare).
Some questions arise here. First, I think you're overcomplicating the situation. For example, it would be easier to have two functions, one that calculates the min and other that calculates the max, and then call either of them depending on the value of isMin.
More so, note how in each iteration you're making the test to see if isMin is true or not, (at least in the "optimized" code you show last) and that comparison could have been done just once.
Now, if isMin can be deduced in any way at compile time, you can use a template class that selects the correct implementation optimized for the case, and without any run-time overhead (not tested, written from memory):
template<bool isMin>
class ExtremeFinder
{
static float FindExtreme(const double* x, const double* y,
const unsigned int n)
{
// Version that calculates when isMin is false
}
};
template<>
class ExtremeFinder<true>
static float FindExtreme(const double* x, const double* y,
const unsigned int n)
{
// Version that calculates when isMin is true
}
};
and call it as ExtremeFinder<test_to_know_isMin>::FindExtreme(...);, or, if you cannot decide it at compile time, you can always do:
if (isMin_should_be_true)
ExtremeFinder<true>::FindExtreme(...);
else
ExtremeFinder<false>::FindExtreme(...);
If you had 2 disjunct criteria, e.g. < and >=, you could use a bool less function argument and use XOR in loop:
if (less ^ (a>=b))
Don't know about performance, but is easy to write.
Or not-covering-all-possibilities-disjunct < and >:
if ( (a!=b) && (less ^ (a>b) )