Passing a vector to constructor in C++
Last Updated :
22 Feb, 2023
When class member is a vector object (not a reference).
We can simply assign in constructor.
CPP
#include <iostream>
#include <vector>
using namespace std;
class MyClass {
vector< int > vec;
public :
MyClass(vector< int > v)
{
vec = v;
}
void print()
{
for ( int i = 0; i < vec.size(); i++)
cout << vec[i] << " ";
}
};
int main()
{
vector< int > vec;
for ( int i = 1; i <= 5; i++)
vec.push_back(i);
MyClass obj(vec);
obj.print();
return 0;
}
|
Time complexity : O(n)
Space complexity : O(n)
We can also initialize using the initializer list.
CPP
#include <iostream>
#include <vector>
using namespace std;
class MyClass {
vector< int > vec;
public :
MyClass(vector< int > v) : vec(v)
{
}
void print()
{
for ( int i = 0; i < vec.size(); i++)
cout << vec[i] << " ";
}
};
int main()
{
vector< int > vec;
for ( int i = 1; i <= 5; i++)
vec.push_back(i);
MyClass obj(vec);
obj.print();
return 0;
}
|
Time complexity : O(n)
Space complexity : O(n)
When class member is a vector a reference.
In C++, references must be initialized using initializer list.
CPP
#include <iostream>
#include <vector>
using namespace std;
class MyClass {
vector< int >& vec;
public :
MyClass(vector< int >& arr)
: vec(arr)
{
}
void print()
{
for ( int i = 0; i < vec.size(); i++)
cout << vec[i] << " ";
}
};
int main()
{
vector< int > vec;
for ( int i = 1; i <= 5; i++)
vec.push_back(i);
MyClass obj(vec);
obj.print();
return 0;
}
|
Time complexity : O(n)
Space complexity : O(n)
Share your thoughts in the comments
Please Login to comment...