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

C++ retrieving an index value in a vector while using min_element or max_element

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

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

传入此函数的两个向量大小相同:我们假设 ratings 向量中没有两个值相等。不能对第二个向量进行排序。

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)];
}

对于 std::vector 或任何其他带有 random-access iterators 的容器,您可以使用算术运算符(为简单起见,我们假设容器不为空):

 auto maxi = std::max_element(ratings.begin(), ratings.end());
 return names[maxi - ratings.begin()];

复杂度:O(1).

对于迭代器至少为 input iterators 的容器,您可以使用 std::distance:

 auto maxi = std::max_element(ratings.begin(), ratings.end());
 return names[std::distance(ratings.begin(), maxi)];

复杂性:O(1) 具有随机访问迭代器,O(n) 没有随机访问。