0

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(), ...);
KKO
  • 1,913
  • 3
  • 27
  • 35

1 Answers1

3

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]) ) ;
P0W
  • 46,614
  • 9
  • 72
  • 119
  • 1
    It looks like OP doesn't have C++11. – juanchopanza Oct 24 '14 at 06:56
  • How do I have a variable number of arguments for the function and call them? So that I could have a for loop to push_back each argument into the vector – KKO Oct 24 '14 at 07:11
  • @POW I like the array version of returning the max better. But again, how do I turn it into a function with a variable number of arguments? – KKO Oct 24 '14 at 07:40
  • 2
    @KKO So since you want everything from SO, here you go http://rextester.com/UGE11198, and please choose the one you want, thanks ! – P0W Oct 24 '14 at 07:51
  • Thank you! I was just trying something like the first maxof. It's exactly what I need – KKO Oct 24 '14 at 07:56