×

Computing index using Pointers Returned by STL Functions in C++

In this tutorial we will learn how to compute index using pointers which returned by STL functions in C++. Many built-in C++ functions return pointers to memory places that provide an address for the requested number but have no relationship to the computed value's actual index in a container. To find the maximum element in a code, for example, we use std::max element(), which returns the memory location rather than the index of the needed element. Because we sometimes need the index corresponding to that address, the following example explains how we can do so.

C++ Program:

// C++ code displaying max element's return value ()
#include <bits/stdc++.h>
using namespace std;


int main ()
{
	// initialization of vector
	vector<int> vi1 = { 2, 4, 5, 7, 3 };


	// printing maximum element
	cout << "The maximum element is : "
		<< ( *max_element ( vi1.begin (), vi1.end () ) );
	// printing the position in memory
	cout << "\nThe position of the maximum element is : ";
	printf ( "%d", max_element ( vi1.begin (), vi1.end () ) );
}

Output:

The maximum element is : 7
The position of the maximum element is : 202059452

The output in the preceding output does not appear to be correct, hence there is a need for methods to compute the exact index of the position of the requested element in the supplied container. These are some examples:

  • Subtracting the first iterator
  • Using std::distance()
  • Subtracting the First Iterator: In this method, we simply subtract the container's beginning pointer, in the case of vectors, the "begin()" iterator that corresponds to the address of the container's first element; by subtracting this, we may obtain the exact index of the needed value with respect to the container.

C++ Program:

// CPP code displaying how to print the exact position after subtracting the first iterator.
#include <bits/stdc++.h>
using namespace std;


int main ()
{
	// initialization vector
	vector<int> vi1 = { 2, 4, 5, 7, 3 };


	// printing the maximum element
	cout << "The max element is : "
		<< ( *max_element ( vi1.begin (), vi1.end () ) );


	// printing the position
	cout << "\nThe position of maximum element is : "
		<< max_element ( vi1.begin (), vi1.end () ) - vi1.begin ();
	;
	return 0;
}

Output:

The max element is : 7
The position of maximum element is : 3
  • Using std::distance() : Another option for computing the desired position is to use distance(), which bypasses the first iterator as the first parameter and the intended point as the second.

C++ Program:

// C++ code showing how to output a precise position using distance ()
#include <bits/stdc++.h>
using namespace std;


int main ()
{
	// initialization of vector
	vector<int> vi1 = { 2, 4, 5, 7, 3 };


	// printing the maximum element
	cout << "The maximum element is : "
		<< ( *max_element ( vi1.begin (), vi1.end () ) );


	// printing the position
	cout << "\nThe position of maximum element is : ";
	cout << distance ( vi1.begin (),max_element ( vi1.begin (), vi1.end () ) );
	return 0;
}

Output:

The maximum element is : 7
The position of maximum element is : 3

Related Topics

C++ Do while loop

In this article, we will discuss the C++ Do-While loop with its syntax, working, key features, algorithm, and examples. Do-While Loop: The do-while loop constitutes a specific style of looping construct in...

5 minutes read.

swap() function in C++

Swap() function: swap() function in C++: swap() function is a pre-define function in c++ present in STL( Standard template library ). It is used to swap two numbers. It takes two mandatory...

6 minutes read.

Implementing the sets without C++ STL containers

Many practical features and tools in C++ support us in programming competitions. One of these parts is a set from the Standard Template Library (STL), which offers an effective way...

6 minutes read.

Web Development in C++

Before learning above C++ web development, we need to learn about CGI What is CGI? CGI stands for common gateway interface. CGI is a standard that tells us how the exchange of...

4 minutes read.

C++ Polymorphism

Polymorphism refers to the fact that something exists in several forms. Polymorphism, in simple terms, is the ability of a message to be presented in several formats. A real-life example...

4 minutes read.

Converting string into integer in C++

When programming in C++, we'll frequently need to change one data type to another. When we use C++ to create apps, we must transform data from one type to another. When...

7 minutes read.

Counting Frequencies of Array Elements in C++

We have an array of integer items with duplicate values, and our objective is to compute the frequencies of the different elements in the array. Methods: Methods that can be used to...

3 minutes read.

Similarities between C++ and Java

People who are preparing for software engineering roles must have come across either one of these languages because as all the companies do not accept python for hiring a fresher...

3 minutes read.

C++ Fork

A new process known as a "child process" is created with the fork system function and runs concurrently with the process that invoked fork() (parent process). Both processes will carry...

4 minutes read.

How to create a button in C++

A button is an option through which a user can control to click a provided input to an application. There are several buttons, each with different styles, to maintain the...

3 minutes read.

C++ Socket Programming

In this world, computer networking has become very important for sharing of data. Every good programmer has some knowledge about computer networking. Socket programming is one of the critical topics...

6 minutes read.

Divide by Zero Exception in C++

We use exception handling method to handle the divide by zero exception. Dividing a number with zero is generally mathematical error. We have to exception handling method to overcome this...

2 minutes read.

Pattern programs in C++

In this article, we are going to discuss different pattern programs in C++. Program for Printing * patterns: Right Angle Triangle* pattern #include <iostream> using namespace std; int main() {     int rows;     cout <<...

3 minutes read.

C++ int into String

Data type conversion is a standard editing process. You may need to convert variable from one type of data to another in a variety of situations. There are two ways...

5 minutes read.

Single dimension array

C++ Array An array is a collection of data (elements) of the same data types. The elements of an array are allocated in contiguous memory allocation. Elements of the array are accessed through...

1 minute read.

Diamond Pattern in C++ using For Loop

For Loop: A for loop is a repetitive control structure that allows you to create a loop for executing a specific number of times. The syntax of for loop: In C++, a for...

5 minutes read.

Structure Vs Class in C++

The structure in C++ is similar to that of a class, with a few exceptions. Both the structure and the stage, the most important thing is safety. The property is...

4 minutes read.

The Stock Span Problem

It is necessary to determine the span of a stock's price throughout all n days in order to solve the stock span problem, which involves a set of n daily...

5 minutes read.

How to Reverse a String in C++ using For Loop

For Loop: We may loop through a certain section of C++ code repeatedly using the for loop. A for loop is carried out if the test expression yields a true result. The...

4 minutes read.

C++ add two numbers using the function

Here we will learn how to add two numbers by creating function in C++. Let’s learn this with help of example. Code: - #include <iostream> using namespace std; int add_two_no(int a, int b); int main(){   int...

1 minute read.