KKO
KKO

Reputation: 1933

Function that returns the max of a variable number of scalars

I need to create a function that takes as an input a variable number of scalars and returns the biggest one. Just like std::max() does for 2 elements, but I need it for an undefined number of elements, can be 2, or 5, or 10 etc.. Any suggestions on how to approach this?

I'm using Visual Studio 2010. I tried with:

std::max({2, 8, 5, 3})

Error: no instance of overloaded function "std::max" matches the argument list

std::vector<int> v {2, 8, 5, 3};

Error: expected a ; (after v)

And more important, if I put this into a function, how do I have a variable number of arguments and how do I call them? I guess it should be somehow with a template?


What I need it for: I'm working with a bunch of vectors, maps, etc. and I need to find out which has the most elements. So I was thinking that I should end up with something like

int biggest = max(vector1.size(), vector2.size(), map1.size(), ...);

Upvotes: 0

Views: 334

Answers (1)

P0W
P0W

Reputation: 47814

Use std::max_element, if you have a container already populated

std::vector<int>::iterator it = std::max_element( vector1.begin(), vector1.end() );

Else use plain array like following :

int a[] = {2, 8, 5, 3 }; // add whatever elements you want
int *pos = std::max_element( a, a+sizeof(a)/sizeof(a[0]) ) ;

Upvotes: 3

Related Questions