我正在处理一个问题,我的代码中有2个向量对象:1是vector<string>
,另一个是vector<unsigned>
,我作为const ref传递给某个函数。我正在使用这些函数来查找一个向量中的最小值或最大值,但我需要min或max的索引值,以便我可以索引到另一个向量。我的代码看起来像这样:
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
向量中没有两个值相等的值。排序第二个向量不是一个选项。
答案 0 :(得分:5)
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)];
}
答案 1 :(得分:4)
对于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 std::distance(ratings.begin(), maxi);
复杂性:O(1)
具有随机访问迭代器,O(n)
具有非随机访问权限。