使用 C++ 中 STL 函数返回的指针计算索引
在本节中,我们将了解如何在 C++ 中使用 STL 返回的指针生成索引。众所周知,C++ 中许多内置函数会返回指向内存位置的指针,该指针提供了所需数字的地址,但它与返回的值在容器中的实际索引无关。例如,要确定代码中的最大元素,我们使用 std::max_element() 函数,它不会返回所需元素的索引,而是返回内存中的地址。但有时,我们需要从该地址获取索引。在这里,我们将了解如何生成索引。
减去第一个迭代器
从容器的 begin() 方法中,我们将获得第一个位置的地址。现在,从返回的地址中减去起始地址,我们可以得到差值。从中我们可以找到索引。
示例
让我们看看以下实现,以便更好地理解 -
#include <bits/stdc++.h>
using namespace std;
int main(){
vector<int> vec = { 10, 40, 50, 60, 30};
cout << "Max element is : " << (*max_element(vec.begin(), vec.end())) << endl;
cout << "The index of maximum element : ";
cout << max_element(vec.begin(), vec.end()) - vec.begin();
}输出
Max element is : 60 The index of maximum element : 3
另一种查找索引的方法是使用 std::distance() 方法。我们将按如下方式使用它 -
示例
#include <bits/stdc++.h>
using namespace std;
int main(){
vector<int< vec = { 10, 40, 50, 60, 30};
cout << "Max element is : " << (*max_element(vec.begin(), vec.end())) << endl;
cout << "The index of maximum element : ";
cout << distance(vec.begin(), max_element(vec.begin(),
vec.end()));
}输出
Max element is : 60 The index of maximum element : 3
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP