c_cpp Cpp / C ++ min,max

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp Cpp / C ++ min,max相关的知识,希望对你有一定的参考价值。

#include <iostream> // std::cout, std::endl
#include <iterator> // std::next
#include <vector>   // std::vector

using std::cout;
using std::endl;
using std::next;
using std::vector;

double cpp_min(vector<double> &x) {                        // `&`: pass `x` by reference
    double out = x.at(0);                                  // out starts `at()` `x`'s first element (v[0] = 1)

    for (auto it = next(begin(x)); it != end(x); ++it) {   // `begin()` returns iterator starting at `x[0]`, `next()` advances 1 position to `x[1]`
        if (*it < out) {                                   // `*` dereferences `it` to access the value to which it points
            out = *it;                                     // if the dereferenced value is less than `out`, out is updated
        }
    }

    return out;
}

double cpp_max(vector<double> &x) {
    double out = x.at(0);

    for (auto it = next(begin(x)); it != end(x); ++it) {
        if (*it > out) {
            out = *it;
        }
    }

    return out;
}

int main() {
    vector<double> v{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };

    double min_result = cpp_min(v);
    double max_result = cpp_max(v);

    cout << "min: " << min_result << endl;
    cout << "max: " << max_result << endl;

    return 0;
}

//> min: 1
//> max: 20

以上是关于c_cpp Cpp / C ++ min,max的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp #rcpp #min #max

c_cpp Rcpp min,max

c_cpp Min Coins

c_cpp 155. Min Stack

c_cpp max.c

c_cpp dlib min_cut