1. 获取vector中的最大值,最小值,及位置索引(max_elements())
<span style="font-size:14px;">#include <algorithm>
#include <iostream>
int main()
{
std::vector<double> v {1.0, 2.0, 3.0, 4.0, 5.0, 1.0, 2.0, 3.0, 4.0, 5.0};
std::vector<double>::iterator biggest = std::max_element(std::begin(v), std::end(v));
std::cout << "Max element is " << *biggest<< " at position " << std::distance(std::begin(v), biggest) << std::endl;
auto smallest = std::min_element(std::begin(v), std::end(v));
std::cout << "min element is " << *smallest<< " at position " << std::distance(std::begin(v), smallest) << std::endl;
} </span>
输出是 Max =5, position 4
Min = 1, position 0
2. 查找某个特定的元素所在的位置。(find())
<span style="font-size:14px;">#include <vector>
#include <algorithm>
#include <iostream>
int main( )
{
using namespace std;
vector<int> L;
L.push_back( 1 );
L.push_back( 2 );
L.push_back( 3 );
L.push_back( 4 );
L.push_back( 5 );
vector<int>::iterator result = find( L.begin( ), L.end( ), 3 ); //查找3
if ( result == L.end( ) ) //没找到
cout << "No" << endl;
else //找到
cout << "Yes" << endl;
}</span>
3. 统计vector中特定元素的个数。(count())
<span style="font-size:14px;">#include <iostream>
#include <vector>
#include <algorithm> // 包含通用算法
using namespace std;
int _tmain( int argc, _TCHAR* argv[])
{
vector< int > scores;
scores.push_back(100);
scores.push_back(80);
scores.push_back(45);
scores.push_back(75);
scores.push_back(99);
scores.push_back(100);
int num = 0;
num= count (scores.begin(),scores.end(),100);//统计100出现的次数
cout<< "times: " <<num<<endl;
return 0;
}</span>