C++ finds the maximum value in vector

After getting used to Python programming, I feel that my head is getting bigger when I go back and write C++. Python is a high-level language, while C++ is a low-level language. So a problem solved in one line of Python may take several lines in C++. For example, the problem of finding the maximum value in a list. If it is Python, then the code will probably look like this.

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

In the end, the result can be output perfectly. It directly calls the max function in the Python standard library.
But in C++ you won't be so lucky. Because vector belongs to the template class in STL, it is a kind of container, and there is no related function defined in it to find the maximum value. So much trouble. The core of operating vector is to use iterators. So the code needs to be written like this:

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

Here, the iterator and the max_element function in the algorithm library are used to find the maximum value in the vector, and by the way, the position of the maximum value is found. The auto here is actually automatically replaced by vector<int>::iteratorthe type at runtime.
Of course, if I don't want to use other library functions to assist calculations, then this may be necessary:

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

This can also be achieved, mainly using the profiteering for traversal, and then use the find function to find the location. Of course, you can also use an iterator to traverse during the for loop, and then record the position of the iterator at the maximum value by the way. The iterator here can be roughly understood as a pointer, but it is different from a pointer in many places.

Guess you like

Origin blog.csdn.net/qxconverse/article/details/67638545