How can the maximum or minimum value be obtained from a vector in C ? Would the same approach work for an array?
In C , several methods are available for finding the maximum or minimum value in a vector or array.
Vectors:
To determine the maximum or minimum value within a vector, utilize the max_element() or min_element() functions from the
<code class="cpp">#include <algorithm> #include <vector> int main() { // Create a vector std::vector<int> vector = {1, 3, 5, 2, 4}; // Find the maximum value std::vector<int>::iterator max_it = std::max_element(vector.begin(), vector.end()); // Print the maximum value std::cout << "Maximum value: " << *max_it << std::endl; return 0; }
Arrays:
For arrays, you can directly use the loop approach:
<code class="cpp">int array[] = {1, 3, 5, 2, 4}; int max_value = array[0]; for (int i = 1; i < sizeof(array) / sizeof(array[0]); i++) { if (array[i] > max_value) { max_value = array[i]; } }</code>
The above is the detailed content of How to Find the Maximum or Minimum Value in a C Vector or Array?. For more information, please follow other related articles on the PHP Chinese website!