C++求最大值和最小值以及對應下標

所用方法

用 algorithm 庫中的

max_element

min_element

這兩個函數返回的是位置指針,*max_element獲得最大值;
*min_element獲得最小值。
 distance(begin(), max_element(, ))獲得最大值的下標。
 distance(begin(), min_element(, ))獲得最小值的下標。

代碼示例

1、普通數組中的用法

#include<iostream>
#include <algorithm>
using namespace std;
int main()

{
	int a[5] = { 12, 3, 65, 74,55 };
	cout << "數組中的最大值爲:" << (*max_element(a, a + 5)) <<"最大值的索引"<< distance(begin(a), max_element(a, a + 5)) << endl;
	cout << "數組中的最小值爲:" << *(min_element(a, a + 5)) <<endl;
	return 0;

}

2、vector中的用法

#include<iostream>
#include<vector>
#include <algorithm>
using namespace std;
int main()
{
	int a[] = { 2, 3, 5, 4, 5 };
	vector<int>b(a, a + 5);
	vector<int>::iterator p = max_element(b.begin(), b.end());
	vector<int>::iterator q = min_element(b.begin(), b.end());
	cout << *p << endl;
	cout << *q << endl;
	system("pause");
	return 0;

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章