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;
}
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐