【发布时间】:2018-05-25 18:29:47
【问题描述】:
我正在处理一个问题,我的代码中有两个向量对象:一个是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返回什么值?你不是在使用它们,而是在取消引用它们。 -
@PaulMcKenzie 没有取消引用它们,它们返回一个指针或迭代器。
-
好的,那么对那个指针和容器的开始做数学运算。
-
@PaulMcKenzie 那是我有点迷路了......在这里摇头;它也应该很简单。
-
@FrancisCugler 您的来电,但请接听。
标签: c++ vector indexing max min