Computing Index Using Pointers Returned By STL Functions in C++
Last Updated :
04 Jan, 2022
Many inbuilt functions in C++ return the pointers to the position in memory which gives an address of the desired number but has no relation with the actual index in a container of the computed value. For example, to find the maximum element in a code, we use std::max_element(), which returns the address in memory, not the index of the desired element. Sometimes, we need the index corresponding to that address, so the following example demonstrates how we can do that,
CPP
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector< int > vi = { 1, 4, 5, 6, 3 };
cout << "The max element is : "
<< (*max_element(vi.begin(), vi.end()));
cout << "\nThe position of maximum element is : " ;
cout<< distance(vi.begin(),max_element(vi.begin(), vi.end()));
return 0;
}
|
Output
The max element is : 6
The position of maximum element is : 2015522492
The output doesn’t look right in the above output so, there is a requirement for having ways to compute the exact index of the position of the desired element in the specified container. These ways are:
1) Subtracting the first iterator
2) Using std::distance()
Subtracting the First Iterator
In this method, we just subtract the beginning pointer of the container, in the case of vectors its “begin()” iterator that points to the address of 1st element of the container, subtracting this we can get the exact index of the required value w.r.t the container.
Output
The max element is : 6
The position of maximum element is : 3
Using distance() is also another alternative to compute the desired position, bypassing the 1st iterator as the first argument and the desired position as the 2nd argument.
CPP
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector< int > vi = { 1, 4, 5, 6, 3 };
cout << "The max element is : "
<< (*max_element(vi.begin(), vi.end()));
cout << "\nThe position of maximum element is : " ;
cout<< distance(vi.begin(),max_element(vi.begin(), vi.end()));
return 0;
}
|
Output
The max element is : 6
The position of maximum element is : 3
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...