Reputation: 73
Below is my code, I am new to C++ please help why this is giving error, I want to find max among element without using any extra space.
Code:
#include <bits/stdc++.h>
using namespace std;
int main() {
cout<<*max_element({4,6,2,5});
}
Error:
error : prog.cpp: In function ‘int main()’:
prog.cpp:5:30: error: no matching function for call to ‘max_element(<brace-enclosed initializer list>)’
cout<<*max_element({4,6,2,5});
^
In file included from /usr/include/c++/5/algorithm:62:0,
from /usr/include/x86_64-linux-gnu/c++/5/bits/stdc++.h:64,
from prog.cpp:1:
/usr/include/c++/5/bits/stl_algo.h:5505:5: note: candidate: template<class _FIter> constexpr _FIter std::max_element(_FIter, _FIter)
max_element(_ForwardIterator __first, _ForwardIterator __last)
^
/usr/include/c++/5/bits/stl_algo.h:5505:5: note: template argument deduction/substitution failed:
prog.cpp:5:30: note: candidate expects 2 arguments, 1 provided
cout<<*max_element({4,6,2,5});
^
In file included from /usr/include/c++/5/algorithm:62:0,
from /usr/include/x86_64-linux-gnu/c++/5/bits/stdc++.h:64,
from prog.cpp:1:
/usr/include/c++/5/bits/stl_algo.h:5529:5: note: candidate: template<class _FIter, class _Compare> constexpr _FIter std::max_element(_FIter, _FIter, _Compare)
max_element(_ForwardIterator __first, _ForwardIterator __last,
^
/usr/include/c++/5/bits/stl_algo.h:5529:5: note: template argument deduction/substitution failed:
prog.cpp:5:30: note: candidate expects 3 arguments, 1 provided
cout<<*max_element({4,6,2,5});
^
Upvotes: 0
Views: 1298
Reputation: 349
you can use max instead of *max_element. Refer below:
cout<<max({4,6,2,5});
It will give your desired output.
Upvotes: 2
Reputation: 3380
std::max_element
uses iterators to iterate through a list to find the maximum element (reference: cppreference). So one way of doing it is by first assigning the values to a vector and then passing its begin and end iterators to the function.
#include <vector>
...
int main() {
std::vector<int> nums = {4,6,2,5};
cout << *max_element(nums.begin(), nums.end());
}
Optionally you can use std::max
to get the max element. It has an overload to take in a initializer list and enables you to get it done as is (reference: cppreference).
int main() {
cout << max({4,6,2,5});
}
Note: Try not to use #include <bits/stdc++.h
as explained in this thread: Why should I not #include <bits/stdc++.h>?
Upvotes: 2