C++ 数组或vector最大值最小值
一)Returns an iterator pointing to the element with the largest value in the range[first,last)[cpp]view plaincopyposition=max_element(a,a+n)-a; 这样写的话就代表的是找到的最大元素的位置在哪里,p
一)
Returns an iterator pointing to the element with the largest value in the range[first,last)
- position=max_element(a,a+n)-a;
- printf("%d\n",*max_element(a,a+n));
同时 min_element的用法同上,但是都有一个共同点,就是找到的位置都是第一个最大(小)的元素,即存在多个相同大小的元素的时候找到的是第一个
1)普通数组用法!
#include <algorithm>
int main()
{int a[5] = { 2, 3, 5, 4, 5 };
cout << (*max_element(a, a + 5)) << endl;
cout << (*(max_element(a, a + 5)+1)) << endl;
system("pause");
return 0;
}
2) vector容器的用法!
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;
}
3)微软一笔试题做法
int main()
{
int a[] = { 2,3,4,9};
vector<int>b(a,a+4);
int sum = 0;
while (b.size() > 1)
{
vector<int>::iterator p = max_element(b.begin(), b.end());
vector<int>::iterator q = min_element(b.begin(), b.end());
if (*p > *q)
{
int dif = (*p - *q);
sum += dif;
b.erase(p);
b.erase(q);
b.push_back(dif);
}
else
{
int dif = (*p - *q);
sum += dif;
b.erase(q);
}
}
cout << sum << endl;
system("pause");
return 0;
}
更多推荐
所有评论(0)