C++求vector中的最大值

4 篇文章 0 订阅
2 篇文章 0 订阅

习惯了Python的编程以后,再回过头来写C++感觉头都被搞大了。Python是一门高级语言,而C++是一门偏底层的语言。所以Python一行解决的问题用C++也许需要好几行。比如在一个列表中找最大值的问题。如果是Python的话,那么代码大概是这样的。

l = [2,4,6,7,1,0,8,9,6,3,2]
print(max(l))

最后就能完美地输出结果,它直接调用的是Python标准库里面的max函数。
但是在C++里面就不会那么幸运了。由于vector属于STL中的模板类,是一种容器,而它里面又没有定义相关的函数求最大值。因此要麻烦很多。而操作vector的核心就是采用迭代器。于是代码需要这样写:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main(){
    vector<int> a = { 2,4,6,7,1,0,8,9,6,3,2 };
    auto maxPosition = max_element(a.begin(), a.end());
    cout << *maxPosition << " at the postion of " << maxPosition - a.begin() <<endl;
    //cout << a[maxPosition - a.begin()] << " at the postion of " << distance(a.begin(), maxPosition) << endl;
    system("pause");
    return 0;
}

这里使用迭代器和algorithm库中的max_element函数来求得vector中的最大值,顺便求出了最大值所在的位置。这里的auto其实在运行的时候就被自动替换为了vector<int>::iterator类型。
当然了,如果说我不想使用其它的库函数来辅助计算,那么可能需要这样:

#include <iostream>
#include <vector>
using namespace std;

int findMax(vector<int> vec) {
    int max = -999;
    for (auto v : vec) {
        if (max < v) max = v;
    }
    return max;
}

int getPositionOfMax(vector<int> vec, int max) {
    auto distance = find(vec.begin(), vec.end(), max);
    return distance - vec.begin();
}

int main(){
    vector<int> a = { 2,4,6,7,1,0,8,9,6,3,2 };
    int maxNumber = findMax(a);
    int position = getPositionOfMax(a, maxNumber);
    cout << maxNumber << " at the postion of " << position << endl;
    system("pause");
    return 0;
}

这样也能实现,主要用到的是暴利for遍历,然后再用find函数找位置。当然也可以在for循环的时候,用迭代器遍历,然后顺便记录最大值时的迭代器的位置,这里的迭代器可以大致理解为指针,但是和指针很多地方不同。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值