我正在处理一个问题,我的代码中有两个 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/