vector的常用方法

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>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值