best way to write a function returning 2 value

So I have a function like the one below
1
2
3
4
5
6
7
bool get_array( float input_param, vector<int>& output_param ){
// some code that handles output_param output

if( error ) return false;

}


So basiclly this function must return 2 value
well one of the value is just a bool returning whether the procedure doesn't fail at some point or not

This feels a bit ugly, not that it works poorly or anything

is there any better way to write this function ?
Another way would be to return a std::pair<bool, std::vector<int>> ...
http://en.cppreference.com/w/cpp/utility/pair
... but in my opinion it makes the code calling the function less nice because you can't name the bool and the vector individually.

Last edited on
ok... I guess this is the only reasonable way of doing that,,
You could use your own struct in place of the std::pair?

Andy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;

struct MyInfo {
	bool        valid; // or whatever
	vector<int> data;
};

MyInfo get_info( float input_param );

int main() {
	cout << boolalpha;
	MyInfo info = get_info(42.0f);
	cout << "info.valid = " << info.valid << endl;
	if(info.valid) {
		const size_t count = info.data.size();
		cout << "info.data.count() = " << count << endl;
		for(size_t index = 0; count > index; ++index) {
			cout << "info.data[" << index << "] = " << info.data[index] << endl;
		}
	}

	return 0;
}

MyInfo get_info( float /*unused_here*/ ) {
	MyInfo info;
	info.valid = true;
	info.data.push_back(1);
	info.data.push_back(2);
	info.data.push_back(3);
	return info;
}


info.valid = true
info.data.count() = 3
info.data[0] = 1
info.data[1] = 2
info.data[2] = 3



it makes the code calling the function less nice because you can't name the bool and the vector individually.

You can name them with a tie (although it's still more than one line):
1
2
3
bool b;
std::vector<int> v;
std::tie(b, v) = get_array(...

the tie solution looks great

but I think I can't return a dereference like
 
const vector<int>& get_data(){ return data; }


I guess I will go with a const pointer in this case ?
I have been wondering the same thing and these are the ideas I have come up with.

break down the function into 2 functions when possible.

or

combine the return values xxx and yyy to return xxxyyy or xxx-yyy.
Breaking it into 2 function is rather a waste of overhead in many cases IMO...

How is combining values xxx and yyy possible ?
I only know how to do that with string but that is also a strange thing to do because why separate them in the first place when It can combined...
Topic archived. No new replies allowed.