Open In App

Computing Index Using Pointers Returned By STL Functions in C++

Improve
Improve
Like Article
Like
Save
Share
Report

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




// C++ code to demonstrate ways to print exact
// position using distance()
#include <bits/stdc++.h>
using namespace std;
 
// Driver Code
int main()
{
    // initializing vector
    vector<int> vi = { 1, 4, 5, 6, 3 };
 
    // printing max element
    cout << "The max element is : "
         << (*max_element(vi.begin(), vi.end()));
 
    // printing position
    // prints wanted position
    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.

CPP





Output

The max element is : 6
The position of maximum element is : 3

Using std::distance()

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




// C++ code to demonstrate ways to print exact
// position using distance()
#include <bits/stdc++.h>
using namespace std;
 
// Driver Code
int main()
{
    // initializing vector
    vector<int> vi = { 1, 4, 5, 6, 3 };
 
    // printing max element
    cout << "The max element is : "
         << (*max_element(vi.begin(), vi.end()));
 
    // printing position
    // prints wanted position
    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

 



Last Updated : 04 Jan, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads