How to implement a function that return two integers?

Pages: 12
I have the following code but it needs to have a function that has a vector as a parameter and return the maximum and minimum of value of n numbers. The vector can only be read ONCE (one iteration) and "cout" has to be in main.

I was able to make a working code but I have no idea how to implement the function I am supposed to do so I would like some help.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <vector>
using namespace std;

int main () {
	int n, min, max;
	cin >> n;
	vector <int> v (n);
	bool first = true;
	for (int i = 0; i < n; ++i) {
		cin >> v[i];
		if (first) {
			min = v[i];
			max = v[i];
			first = false;
		}
		else {
			if (v[i] < min) min = v[i];
			if (v[i] > max) max = v[i];
		}
	}
	cout << max << " " << min << endl;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <vector>
#include <tuple>
#include <algorithm>

template <typename T>
std::pair<T, T> twoFromOne (std::vector<T>& vec)
{
    std::sort(vec.begin(), vec.end());
    return  {std::make_pair(vec[0], vec[vec.size()-1])};
}

int main()
{
    std::vector<int> vec {1, 3, 4, 9, 8, 5};
    std::cout << twoFromOne(vec).first << " " << twoFromOne(vec).second << "\n";
}

Last edited on
Program doesn't compile: extended initializer lists only available with -std=c++11 or -std=gnu++11
Code must be in C++ not C++11
Last edited on
it's not that hard to do some research yourself , no?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <vector>
#include <tuple>
#include <algorithm>

template <typename T>
std::pair<T, T> twoFromOne (std::vector<T>& vec)
{
    std::sort(vec.begin(), vec.end());
    std::pair<T, T> p = std::make_pair(vec[0], vec[vec.size()-1]);
    return p;
  //  return  {std::make_pair(vec[0], vec[vec.size()-1])};
}

int main()
{
    std::vector<int> vec {1, 3, 4, 9, 8, 5};
    std::cout << twoFromOne(vec).first << " " << twoFromOne(vec).second << "\n";
}


Code must be in C++ not C++11
:))
I did some research but I did not found anything useful even if you don't believe me.
Again same error, you can just give me instructions or hints on how to do it though.

First of all, what type of functions allow returning more than one results, two integers in this case?
Last edited on
Seems I could create a working code thanks to you because you showed me the function "pair" that I did not know about, it seems quite useful.

Anyway here is the final code
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
#include <iostream>
#include <vector>
using namespace std;

pair <int, int> function (vector <int> v, int n) {
	pair <int, int> values;
	bool first = true;
	for (int i = 0; i < n; ++i) {
		cin >> v[i];
		if (first) {
			values.first = v[i]; //values.first = max
			values.second = v[i]; //values.second = min
			first = false;
		}
		else {
			if (v[i] > values.first) values.first = v[i];
			if (v[i] < values.second) values.second = v[i];
		}
	}
	return values;
}

int main () {
	int n;
	cin >> n;
	vector <int> v (n);
	pair <int, int> result = function (v, n);
	cout << result.first << " " << result.second << endl;
}


Even if I have made the code I would like someone if could answer me the previous question I made: "What type of functions allow returning more than one results?"
Last edited on
well done you, see it wasn't that difficult
the following link has a useful summary of returning multiple values from a single function:
http://stackoverflow.com/questions/321068/returning-multiple-values-from-a-c-function
(link info goes right up to C++17 which, incidentally, is also C++ believe it or not!)
personally I"d suggest returning struct or class objects with multiple values embedded in them and if you overload the insertion operator << for the struct or class then you can std::cout right within main() to print as many data-members as you wish
link for << opertor overload:
https://www.tutorialspoint.com/cplusplus/input_output_operators_overloading.htm
You can't do it, is the bottom line. Functions return 1 thing.
You can return ONE construct that contains 2, 3, 10000000 or whatever things.

Some ways to do what you want:

you can modify any number of input references:
void foo (int input, int &output1, int *output2) //output1 and output2 can be returned back to the caller. Its not a true "return" but conceptually, it gets the job done.

you can use a pointer:

int * foo(... //foo can return N integers, as a C array/pointer concept

you can use a c++ type.

vector <int> foo(int input)
{
vector <int> v;
... return v.


you can make your own things..
struct ret2 //or a class
{
int one;
int two;
};

ret2 foo(...

etc.

you can even make them different things:

struct retstuff //or a class
{
int one;
double two;
string s;
ret2 r;
};
retstuff foo(...

But in every case, the pattern is the same:

onething foo(parameters...)

and never

one, two foo(...

or anything like that.



I was originally planning to solve the problem with a struct but since I must have a vector in the function parameter and the function also had to had some code, I thought it was impossible and I had no idea what to do.

Am I right it was impossible to do it with structs in this case?

If i have to return 3 or more values in a function without parameters, struct would be the smartest idea or is there something more useful?

What if I also have to return 3 or more values in a function but this time with some parameters. What should I use in this case?

I would be glad if you answer this too.
You can have any combination of return types and parameters; there's no real limit on that.

Remember, a struct or class behave in the same way as any other int or bool, just with more functionality. Pretty much anywhere you can have int you can replace that with MyBigClass.

For example:
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
#include <iostream>
#include <string>

// primitive types
int foo(int param1, int param2, int param3) {
    int ret;
    ret = param1 + param2 + param3;
    return ret;
}

// complex types - notice how apart from the names of the
// types and how I use them its the same as primitive types
struct record {
    int id;
    std::string name;
    double weight;
};

record makeRecord(int id, std::string name, double weight) {
    record ret;
    ret.id = id;
    ret.name = name;
    ret.weight = weight;
    return ret;
}

// using functions
int main() {
    int x = foo(1, 2, 3);
    record r = makeRecord(1, "Bob", 85.0);
    std::cout << x << std::endl;
    std::cout << r.id << " " << r.name << " " << r.weight << std::endl;
    return 0;
}
6
1 Bob 85


Do you kind of get it now? Basically, when you wish to return multiple parameters, the normal idiom is to either return it as some kind of struct or class that usefully defines what you're giving, or use a std::pair or std::tuple.

As @jonnin referred to in his post, there are other ways of getting around the "no returning more than one parameter" rule, but I don't think that was your question, was it.
Last edited on
> If i have to return 3 or more values in a function without parameters,
> struct would be the smartest idea or is there something more useful?

If these three values are going to be used together many times, use a struct with semantically rich names for the members. If it is an isolated case, std::tuple<> comes in handy.
http://en.cppreference.com/w/cpp/utility/tuple

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
#include <iostream>
#include <vector>
#include <stdexcept>
#include <algorithm>
#include <tuple>
#include <numeric>

std::pair<int,int> min_max( const std::vector<int>& seq )
{
    if( seq.empty() ) throw std::domain_error( "min_max of empty sequence" ) ;

    const auto iters = std::minmax_element( std::begin(seq), std::end(seq) ) ;
    return { *iters.first, *iters.second } ;
}

std::tuple<int,int,double> min_max_avg( const std::vector<int>& seq )
{
    const auto mm_pair = min_max(seq) ;
    const auto sum = std::accumulate( std::begin(seq), std::end(seq), 0LL ) ;
    return std::make_tuple( mm_pair.first, mm_pair.second, double(sum) / seq.size() ) ;
}

int main()
{
    const auto tup = min_max_avg( { 7, 2, 9, 4, 0, 5, 1, 6, 8, 3 } ) ;
    std::cout << "min: " << std::get<0>(tup) << '\n'
              << "max: " << std::get<1>(tup) << '\n'
              << "avg: " << std::get<double>(tup) << '\n' ;
}

http://coliru.stacked-crooked.com/a/27a95281ac486a0b
Anyway as you have said that was not my question so I will say it again trying to explain myself better:

Let's say I need to create a function that needs to take parameters from main program (vector, int, etc.) and this function needs to return multiple variables. If this function would only need 2 variables I would use pair as gunnerfunner suggested but what can I do if I need to return 3 or more variables? I cannot use structs in this case right? So what are my options?

Aren't tuples part of C++11? I need "stuff" that works in C++
Last edited on
Look at the code in my last post. I used a struct to return 3 variables in the function at line 19; using structs in that case is fine. Or you could use a std::tuple; see @JLBorges' post. Note that std::tuple needs C++11, though, but you really should be using a compiler that supports that anyway.
Last edited on
Yeah I saw your code but nobody is answering my other question about returning multiple variables with functions with parameters...

Actually, JLBorges did but I cannot use C++11, programming rules of my university
Last edited on
Didn't I? I'm pretty sure I did; what is your understanding of what "functions with parameters" means? Again, my function on line 19 returns three values and takes three parameters; it just happens to return all three parameters unchanged.
Well, I will test it and tell you if it works.

Seems it works:

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
#include <iostream>
#include <vector>
using namespace std;

struct values {
	int min;
	int max;
};

values function (vector <int> v, int n) {
	values result;
	bool first = true;
	for (int i = 0; i < n; ++i) {
		cin >> v[i];
		if (first) {
			result.max = v[i];
			result.min = v[i];
			first = false;
		}
		else {
			if (v[i] > result.max) result.max = v[i];
			if (v[i] < result.min) result.min = v[i];
		}
	}
	return result;
}

int main () {
	int n;
	cin >> n;
	vector <int> v (n);
	values result = function (v, n);
	cout << result.max << " " << result.min << endl;
}


So now that we cleared all the discussion about structs are there other constructs able to do the same for C++?
Last edited on
I gave you pretty much everything from c++.

c++ 11 is just 2011 standard. It isn't exactly cutting edge... thing being 2017... but if its banned, everything I gave you worked in 2000.

class, struct, pointer, stl container, or return in by reference parameters. That's pretty much it. I suppose there is are a few more weird ones, you could put them in a global variable, or a shared memory space, or use assembler to push them on the call stack (which is probably possible in c++ without assembler with some hackish code). You can store anything "manually" by "serializing" it into a byte pointer. But we are way, way into the 'just because you can do something' dark alleys here.




Last edited on
Thanks for the info and thank you all for your help.

I guess that when I advance in C++ they will let me use C++11 but at the moment sticking with the basic stuff
> Aren't tuples part of C++11?

Yes.


> I need "stuff" that works in C++

As of now, C++14 is C++; C++ is C++14.


We can do something desperate (nested pairs) like:
1
2
std::pair<int,int> min_max( const std::vector<int>& seq ) ;
std::pair< std::pair<int,int>, double > min_max_avg( const std::vector<int>& seq ) ;


In legacy C++, it may be better to make the code more readable by polluting the namespace with a one-off custom struct.

(I presume that your career teachers who are not interested in learning anything more would not want to have anything to do with boost::tuple either.)
http://www.boost.org/doc/libs/1_63_0/libs/tuple/doc/tuple_users_guide.html
Why not use references if you want to return multiple variables? Simple and effective.
Pages: 12