一、一个函数获得容器中最大/最小值 方法:使用max_element(A, A+N),此外min_element(A, A+N)可以用来找最小的元素。 以下只举了数组的例子,当然对vector、string这样的对象也是可以进行操作的,但这里不再演示。
#include <stdio.h> #include <algorithm> using namespace std; int main() { char ch[5] = {'a','b','c','e','f'}; int pos = max_element(ch, ch+5) - ch; printf("The biggest character's index is %d\n", pos); char it = *max_element(ch, ch+5); printf("The biggest character is %c\n", it); int arr[5] = {0, 1, 2, 4, 3}; int posNum = max_element(arr, arr+5) - arr; printf("The biggest number's index is %d\n", posNum); int number = *max_element(arr, arr+5); printf("The biggest number is %d\n", number); system("pause"); return 0; }