📌  相关文章
📜  从向量 c++ 中获取最小和最大元素索引(1)

📅  最后修改于: 2023-12-03 15:21:56.516000             🧑  作者: Mango

从向量 c++ 中获取最小和最大元素索引

C++中,标准库提供了一个minmax_element函数,可以方便地获取一个序列(包括向量)的最小和最大元素以及其对应的迭代器(即索引),相关函数定义如下:

template< class ForwardIt >
std::pair<ForwardIt,ForwardIt> minmax_element( ForwardIt first, ForwardIt last );

template< class ForwardIt, class Compare >
std::pair<ForwardIt,ForwardIt> minmax_element( ForwardIt first, ForwardIt last, Compare comp );

其中,第一个函数使用默认的比较函数std::less,而第二个函数可以传入一个比较函数。返回值是一个std::pair对象,包含最小和最大元素的迭代器。

下面是一个使用示例:

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> v{ 3, 2, 1, 4, 5 };
    auto p = std::minmax_element(v.begin(), v.end());
    std::cout << "Min: " << *p.first << " at index " << std::distance(v.begin(), p.first) << std::endl;
    std::cout << "Max: " << *p.second << " at index " << std::distance(v.begin(), p.second) << std::endl;
    return 0;
}

输出如下:

Min: 1 at index 2
Max: 5 at index 4

注意,返回的是最小和最大元素的迭代器,可以通过std::distance函数获取其对应的索引。

如果需要自定义比较函数,可以传入一个可调用对象(如函数指针、lambda表达式等)作为第二个参数。比如,如果要查找最小正数和最大负数的位置,可以这样写:

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> v{ 3, -2, 1, 4, -5 };
    auto p = std::minmax_element(v.begin(), v.end(), [](int a, int b) {
        if (a > 0 && b > 0) return a < b;
        if (a < 0 && b < 0) return a > b;
        return a > 0;
    });
    std::cout << "Min positive: " << *p.first << " at index " << std::distance(v.begin(), p.first) << std::endl;
    std::cout << "Max negative: " << *p.second << " at index " << std::distance(v.begin(), p.second) << std::endl;
    return 0;
}

输出如下:

Min positive: 1 at index 2
Max negative: -2 at index 1

以上就是在 C++ 中获取向量(或其他序列)中最小和最大元素的方法及示例。