How to return the max element in vector

Ques in Programming and principles in c++ ch 8
10. Write a function maxv() that returns the largest element of a vector argument.
What i tried..(not work)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  #include "std_lib_facilities.h"

auto maxv(const vector<auto>& v){
	auto max = v[0];
	for(int i = 0; i < v.size(); i++)
		if(v[i] > max)
			max = v[i];

	return max;
}

int main(){
	vector<int> maam = {1,2,3,4,5,6};
	std::cout << maxv(maam);
}
Last edited on
This works:
1
2
3
4
5
6
7
8
9
int maxv (const vector<int> &v)
{
  auto max = v[0];
  for (int i = 1; i < v.size (); i++)
    if (v[i] > max)
      max = v[i];

  return max;
}
You need to have GCC 6.0 (not actually released, yet) along with the -std=c++1z flag to enable using auto as you did on line 3. Placeholder auto is part of the Concepts TS, which will only become part of the standard with C++17.

You can get the same effect like this, instead:
1
2
3
4
5
6
template <typename T>
auto maxv(const std::vector<T>& v) {
    auto max = v[0];
    // ...
    return max;
} 
Last edited on
Thanks for replies, you people are very helpful.
Topic archived. No new replies allowed.