Computing index using pointers returned by STL functions in C++

C++Server Side ProgrammingProgramming

In this section we will see how to generate index using pointers that are returned by STL in C++. As we know many inbuilt functions in C++ return the pointers to the position in memory which provides the address of desired number, but it has no relation with the actual index in the container of the returned value. As an example, to determine maximum element in a code, we use std::max_element() function, this does not return the index of the desired element, but return the address in memory. But sometimes, we need to get the index from that address. Here we will see how we can generate the index.

Subtracting first iterator

From the container.begin() method we will get the address of the first position. Now subtracting the start address from the returned address we can get the difference. From there we can find the index.

Example

Let us see the following implementation to get better understanding −

 Live Demo

#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();
}

Output

Max element is : 60
The index of maximum element : 3

Another way to find index is using the std::distance() method. We will use it as below −

Example

 Live Demo

#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()));
}

Output

Max element is : 60
The index of maximum element : 3
raja
Published on 27-Aug-2020 13:38:19
Advertisements