Open In App

Using Non-Member Friend Functions With Vector in C++ STL

Last Updated : 14 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, Non-member buddy functions may access a class’s private members while not being members. The class definition declares them friend. Vector containers, dynamic arrays in C++ Standard Library (STL), may dynamically resize as members are added or deleted. You may need to establish a new class with a vector to utilize non-member friend methods on vector data.

Example:

C++




// C++ Program to use a non-member friend function with a
// custom VectorWrapper class that contains a vector from
// the C++ STL:
#include <iostream>
#include <vector>
  
// Custom class containing a vector
class VectorWrapper {
private:
    std::vector<int> data;
  
public:
    // Constructor
    VectorWrapper(const std::vector<int>& initialValues)
        : data(initialValues)
    {
    }
  
    // Declare a non-member friend function
    friend void printVector(const VectorWrapper& vw);
};
  
// Non-member friend function that has access to
// VectorWrapper's private members
void printVector(const VectorWrapper& vw)
{
    std::cout << "Vector elements: ";
    for (int value : vw.data) {
        std::cout << value << " ";
    }
    std::cout << std::endl;
}
  
int main()
{
    std::vector<int> initialValues = { 1, 2, 3, 4, 5 };
    VectorWrapper vw(initialValues);
    // Prints "Vector elements: 1 2 3 4 5"
    printVector(vw);
  
    return 0;
}


Output

Vector elements: 1 2 3 4 5 

Explanation of the above program

In the above example, we have created a Vector Wrapper class that has a private vector named data. We have declared a non-member friend function printVector() that can access and print the vector data. This is just a simple example, and you can use a similar approach to create more complex friend functions to manipulate the vector data in the custom class.

Time Complexity: O(n)

Space difficulty: O(1) 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads