Accessing std::vector Methods using Pointers in C++

We can access the member functions of a std::vector from a pointer to the vector in a similar way as we access member functions from an object, but with a difference that we have to use arrow operator (->) instead of the dot operator (.) to access its members (both functions and variables).

Syntax to Access Member Functions From Pointer

pointerName->memberFunction(args);

Here,

  • pointerName is the name of the pointer to the vector.
  • memberFunction is the name of the member function that we want to access.
  • args is the arguments if any

C++ Program to Access Member Functions From Pointer to a Vector

The below program demonstrates how we can access member functions from a pointer to a vector in C++.

C++
// C++ program to access member function from pointer to a
// vector
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    // Declaring a pointer to a vector
    vector<int>* vectorPtr = new vector<int>();

    // Adding elements to the vector
    vectorPtr->push_back(10);
    vectorPtr->push_back(20);
    vectorPtr->push_back(30);

    // Accessing and printing data using pointer
    cout << "Elements of vector: ";
    for (int i = 0; i < vectorPtr->size(); ++i) {
        cout << (*vectorPtr)[i] << " ";
    }

    return 0;
}

Output
Elements of vector: 10 20 30 

Time Complexity: O(1)
Auxilliary Space: O(1)

 

 


How to Access Vector Methods from Pointer to Vector in C++?

In C++, we can create a pointer that points to the object of vector type. In this article, we will learn how to access member functions of std::vector from a pointer to the vector in C++.

Example

Input:
vec = {1, 2, 3, 4}
vector<int>* ptr = vec

Output:
ptr->at(2): 3

Similar Reads

Accessing std::vector Methods using Pointers in C++

We can access the member functions of a std::vector from a pointer to the vector in a similar way as we access member functions from an object, but with a difference that we have to use arrow operator (->) instead of the dot operator (.) to access its members (both functions and variables)....

Contact Us