1 获取std::vector中的最小值最大值以及对应的索引

1.1 普通方法

普通方法就是遍历std::vector,对vector中的值进行一一对比,找出最小值、最大值及其对应的索引,示例代码如下

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

int main()
{
    std::vector<float> example_vector = {1.3,0.5,3.2,4.5,6.5,8.9,6.2,10.7,2.3};

    // 找出最小值以及最小值索引
    float min_value = std::numeric_limits<float>::max();
    int min_value_index = -1;

    for (int i = 0; i < example_vector.size(); ++i)
    {
        if (example_vector[i] < min_value)
        {
            min_value = example_vector[i];
            min_value_index = i;
        }
    }

    std::cout << "min_value_index = " << min_value_index << ", min_value = " << min_value << std::endl;

    // 找出最大值以及最大值索引
    float max_value = std::numeric_limits<float>::min();
    int max_value_index = -1;

    for (int i = 0; i < example_vector.size(); ++i)
    {
        if (example_vector[i] > max_value)
        {
            max_value = example_vector[i];
            max_value_index = i;
        }
    }

    std::cout << "max_value_index = " << max_value_index << ", max_value = " << max_value << std::endl;

    return 0;
}

程序输出:

min_value_index = 1, min_value = 0.5
max_value_index = 7, max_value = 10.7

1.2 使用algorithm

我们可以使用algorithm中的std::min_elementstd::max_element的方法获取最大值最小值,然后使用std::distance获取迭代器对应的在std::vector中的索引,示例代码如下:

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

int main()
{
    std::vector<float> example_vector = {1.3,0.5,3.2,4.5,6.5,8.9,6.2,10.7,2.3};

    // 找出最小值
    std::vector<float>::iterator smallest = std::min_element(example_vector.begin(), example_vector.end());

    float min_value = *smallest;

    // 获取最小值索引
    int min_value_index = std::distance(example_vector.begin(), smallest);

    std::cout << "min_value_index = " << min_value_index <<", min_value = "<< min_value << std::endl;


    // 找出最大值
    std::vector<float>::iterator biggest = std::max_element(example_vector.begin(), example_vector.end());

    float max_value = *biggest;

    // 获取最大值索引
    int max_value_index = std::distance(example_vector.begin(), biggest);

    std::cout << "max_value_index = " << max_value_index << ", max_value = " << max_value << std::endl;

    return 0;
}

程序输出:

min_value_index = 1, min_value = 0.5
max_value_index = 7, max_value = 10.7