Finding Maximum or Minimum Values in Vectors in C
Getting the maximum or minimum value from a vector in C is a common programming task. Let's explore how to achieve this and address a specific error related to the max_element function.
Using max_element
The max_element function from the
Addressing the Error
The error you encountered is caused by trying to use the begin() method on an array. Arrays do not have a begin() or end() method like vectors. To work with arrays, you must use standard C-style indexing.
Example for Vectors
<code class="cpp">#include <vector> #include <algorithm> int main() { std::vector<int> vector = {1, 2, 3, 4, 5}; int max_value = *std::max_element(vector.begin(), vector.end()); std::cout << "Maximum value: " << max_value << std::endl; return 0; }
Example for Arrays
<code class="cpp">#include <array> int main() { std::array<int, 5> array = {1, 2, 3, 4, 5}; int max_value = 0; // Initialize to minimum possible value for (int i = 0; i < array.size(); i++) { if (array[i] > max_value) { max_value = array[i]; } } std::cout << "Maximum value: " << max_value << std::endl; return 0; }</code>
The above is the detailed content of How to Find the Maximum or Minimum Value in a C Vector?. For more information, please follow other related articles on the PHP Chinese website!