如何按大小顺序获取vector的索引
时间: 2024-04-15 12:24:11 浏览: 11
要按照大小顺序获取vector中元素的索引,可以使用以下步骤:
1. 创建一个新的vector来保存原始vector的索引。
2. 使用`std::sort`函数对新的索引向量进行排序,并提供一个自定义的比较函数,该函数比较原始向量中对应索引位置的元素。
3. 遍历排序后的索引向量,并打印或使用索引来访问原始向量中的元素。
以下是一个示例代码:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
bool compare(const int& a, const int& b, const std::vector<int>& numbers) {
return numbers[a] < numbers[b];
}
int main() {
std::vector<int> numbers = {5, 2, 8, 4, 9};
std::vector<int> indices(numbers.size());
// 初始化索引向量
for (size_t i = 0; i < indices.size(); i++) {
indices[i] = i;
}
// 使用std::sort和自定义比较函数对索引向量排序
std::sort(indices.begin(), indices.end(), [&](int a, int b) {
return compare(a, b, numbers);
});
// 遍历排序后的索引向量并打印或使用索引访问原始向量中的元素
for (const auto& index : indices) {
std::cout << "索引: " << index << ", 值: " << numbers[index] << std::endl;
}
return 0;
}
```
在这个例子中,我们创建了一个整数向量`numbers`,其中包含一些数字。然后,我们创建一个新的索引向量`indices`,并将其初始化为原始向量的索引。接下来,使用`std::sort`函数对索引向量进行排序,并传递一个自定义的比较函数来比较原始向量中对应索引位置的元素。最后,我们遍历排序后的索引向量,并打印或使用索引来访问原始向量中的元素。
请注意,自定义的比较函数`compare`用于比较原始向量中对应索引位置的元素。在这个例子中,我们使用简单的小于比较,但您可以根据需要自定义比较函数。