Using Non-Member Friend Functions With Vector in C++ STL
Last Updated :
14 May, 2023
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++
#include <iostream>
#include <vector>
class VectorWrapper {
private :
std::vector< int > data;
public :
VectorWrapper( const std::vector< int >& initialValues)
: data(initialValues)
{
}
friend void printVector( const VectorWrapper& vw);
};
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);
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)
Share your thoughts in the comments
Please Login to comment...