Passing a vector to constructor in C++
When class member is a vector object (not a reference).
We can simply assign in constructor.
// Passing vector object to a constructor. #include <iostream> #include <vector> using namespace std; class MyClass { vector<int> vec; public: MyClass(vector<int> v) { vec = v; } void print() { /// print the value of vector 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; } |
chevron_right
filter_none
Output:
1 2 3 4 5
We can also initialize using initialer list.
// Initializing vector object using initializer // list. #include <iostream> #include <vector> using namespace std; class MyClass { vector<int> vec; public: MyClass(vector<int> v) : vec(v) { } void print() { /// print the value of vector 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; } |
chevron_right
filter_none
Output:
1 2 3 4 5
When class member is a vector a reference.
In C++, references must be initialized using initializer list.
// CPP program to initialize a vector reference. #include <iostream> #include <vector> using namespace std; class MyClass { vector<int>& vec; public: // this is the right way to assign // the reference of stl container MyClass(vector<int>& arr) : vec(arr) { } void print() { /// print the value of vector 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; } |
chevron_right
filter_none
Output:
1 2 3 4 5
Recommended Posts:
- Passing vector to a function in C++
- Passing by pointer Vs Passing by Reference in C++
- vector::push_back() and vector::pop_back() in C++ STL
- vector::crend() & vector::crbegin() with example
- vector :: cbegin() and vector :: cend() in C++ STL
- vector::empty() and vector::size() in C++ STL
- vector::front() and vector::back() in C++ STL
- vector::at() and vector::swap() in C++ STL
- vector::begin() and vector::end() in C++ STL
- Passing and Returning Objects in C++
- How to delete an element from the Set by passing its value in C++
- Parameter Passing Techniques in C/C++
- Passing Reference to a Pointer in C++
- Can a constructor be private in C++ ?
- Constructor Delegation in C++
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



