Many inbuilt functions in C++ return the pointers to the position in memory which gives an address of desired number, but has no relation with the actual index in container of the computed value. For eg. to find maximum element in a code, we use std::max_element(), which returns the address in memory, not the index of the desired element.
// C++ code to demonstrate return value of // max_element() #include <bits/stdc++.h> using namespace std; 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 position in memory cout << "\not_eqThe position of maximum element is : " ; printf ( "%d" , max_element(vi.begin(), vi.end())); } |
Output:
The max element is : 6 The position of maximum element is : 9583660
There is requirement for having ways to compute the exact index of the position of desired element in the specified container. These ways have been discussed in this article.
In this method, we just subtract the beginning pointer of the container, in 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.
// C++ code to demonstrate ways to print exact // position by subtracting 1st address #include <bits/stdc++.h> using namespace std; 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 : " ; printf ( "%d" , max_element(vi.begin(), vi.end()) - vi.begin()); return 0; } |
Output:
The max element is : 6 The position of maximum element is : 3
Using distance() is also another alternative to compute the desired position, by passing the 1st iterator as first argument and the desired position as 2nd argument.
// C++ code to demonstrate ways to print exact // position using distance() #include <bits/stdc++.h> using namespace std; 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 : " ; printf ( "%d" , distance(vi.begin(), max_element(vi.begin(), vi.end()))); return 0; } |
Output:
The max element is : 6 The position of maximum element is : 3
Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.