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

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

本文关键字:element 向量 索引值 检索 max 使用 min C++      更新时间:2023-10-16

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

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或任何其他具有随机访问迭代器的容器,您可以使用算术运算符(为简单起见,我们假设容器不为空):

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

复杂度:O(1)

对于迭代器至少是输入迭代器的容器,可以使用std::distance

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

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