Skip to content
Related Articles

Related Articles

Improve Article

Passing a vector to constructor in C++

  • Difficulty Level : Hard
  • Last Updated : 28 Jan, 2018
Geek Week

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;
}
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;
}
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;
}
Output:
1 2 3 4 5
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :