vector 寻找最大值位置

本文介绍如何使用C++标准库中的<algorithm>头文件来查找vector容器中的最大值和最小值元素,并演示了如何进行排序及逆序操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vector<double> dv;
假设dv 的数值已经赋值好了。
最大值所在的位置是
pos = (int) ( max_element(dv.begin(),dv.end()) - dv.begin() );

说明:
max_element(dv.begin(),dv.end()) 返回的是vector<double>::iterator, 相当于指针
的位置,减去初始指针的位置 就得到我们需要的。

以后要用最大值即可以使用 dv[pos]. 

------------------------------------------------------

一个更加详细的例子见:
Josuttis, Nicolai M.
The C++ standard library: a tutorial and reference / Nicolai M. Josuttis.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<int> coll;
vector<int>::iterator pos;
//构造向量 coll = {2,5,4,1,6,3}
coll.push_back(2);
coll.push_back(5);
coll.push_back(4);
coll.push_back(1);
coll.push_back(6);
coll.push_back(3);
//找到最小值和最大值的并打印出来
pos = min_element (coll.begin(), coll.end());
cout << "minimum: " << *pos << endl;
pos = max_element (coll.begin(), coll.end());
cout << "maximum: " << *pos << endl;
//排序
sort (coll.begin(), coll.end());
//find the first element with value 3
The C++ Standard Library
dyne-book 90
pos = find (coll.begin(), coll.end(), //range
3); //value
//reverse the order of the found element with value 3 and all
following elements
reverse (pos, coll.end());
//print all elements
for (pos=coll.begin(); pos!=coll.end(); ++pos) {
cout << *pos << ' ' ;
}
cout << endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值