C++使用 min_element 或 max_element 时检索向量中的索引值
C++ retrieving an index value in a vector while using min_element or max_element
我正在这里解决一个问题,我的代码中有两个向量对象:一个是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)
非随机访问。
相关文章:
- 写入向量<向量<bool>>
- 函数向量_指针有不同的原型,我可以构建一个吗
- std::向量与传递值的动态数组
- 将值指定给向量(2D)的向量中的某个位置
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 如何使用向量的template_back函数
- 尝试通过多个向量访问变量时,向量下标超出范围
- 如何通过派生类函数更改基类中的向量
- C++从另一个类访问公共静态向量的正确方法是什么
- 如何将ampl中的集合表示为c++中的向量
- 变量没有改变?通过向量的函数调用
- 迭代时从向量和内存中删除对象
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 计算排序向量的向量中唯一值的计数
- 矩阵向量乘法(cublasDgemv)返回零
- 一对向量构造函数:初始值设定项列表与显式构造
- 将结构向量排序为子组
- 在C++中调整向量中的索引
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么