
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Compute Index Using Pointers Returned by STL Functions in C++
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 −
#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
#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