C++ 在使用 min_element 或 max_element 时检索 vector 中的索引值

标签 c++ vector indexing max min

我正在处理一个问题,我的代码中有两个 vector 对象:一个是 vector<string> , 另一个 vector<unsigned>我将作为 const ref 传递给某个函数。我正在使用这些函数从一个 vector 中找出最小值或最大值,但我需要最小值或最大值的索引值,以便我可以索引到另一个 vector 。我的代码看起来像这样:

std::string getTopEmployee( const std::vector<std::string>& names, const std::vector<unsigned>& ratings ) {
    // Find Largest Value in ratings
    std::size_t largest = *std::max_element( ratings.begin(), ratings.end() );
    // How to get the index?
    // I do not need the largest value itself.

    return names[index];
}

std::string getWorstEmployee( const std::vector<std::string>& names, const std::vector<unsigned>& ratings ) {

   // Find Smallest Value in ratings
   std::size_t smallest = *std::min_element( ratings.begin(), ratings.end() );
    // How to get the index?
    // I do not need the smallest value itself.

    return names[index];
}

传入此函数的两个 vector 大小相同:我们假设 ratings 中没有两个值值相等的 vector 。对第二个 vector 进行排序不是一种选择。

最佳答案

std::min_element()std::max_element() 使用迭代器,而不是索引。

对于像 std::vector 这样的可索引容器,您可以使用 std::distance() 将迭代器转换为索引。 ,例如:

std::string getTopEmployee( const std::vector<std::string>& names, const std::vector<unsigned>& ratings ) {
    // Find Largest Value in ratings
    auto largest = std::max_element( ratings.begin(), ratings.end() );
    if (largest == ratings.end()) return "";
    return names[std::distance(ratings.begin(), largest)];
}

std::string getWorstEmployee( const std::vector<std::string>& names, const std::vector<unsigned>& ratings ) {
    // Find Smallest Value in ratings
    auto smallest = std::min_element( ratings.begin(), ratings.end() );
    if (smallest == ratings.end()) return "";
    return names[std::distance(ratings.begin(), smallest)];
}

关于C++ 在使用 min_element 或 max_element 时检索 vector 中的索引值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47766388/

相关文章:

c++ - 是否可以在 Qt 中使用带下划线的字母作为键盘快捷键?

c++ - 将 std::wstring 拆分为 std::vector

c++ - 如何检查数字序列是否在C++中具有增加/减少趋势

c++ - 正确别名 vector

python - python数据框中的日期时间索引

mysql - 如何加快 Rails 中的 find_or_initialize 速度?

python - 在python中生成索引列表的方式之间的区别

C++ 继承获取错误

c++ - 如何访问内存映射 USB 主机 Controller 寄存器?

c++ - 将用户输入的字符串大写