How to pass vector to constructor in C++

2 Answers

0 votes
#include <iostream>
#include <vector>

using namespace std; 
  
class Test { 
    vector<int> vec; 
  
public: 
    Test(vector<int> v) { 
       vec = v; 
    } 
    void print()  { 
        for (auto const& v : vec) cout << v << " ";
    } 
}; 
  
int main() 
{ 
    vector<int> vec; 
    
    for (int i = 1; i <= 7; i++) 
        vec.push_back(i); 
        
    Test obj(vec); 
    obj.print(); 
    
    return 0; 
} 


/*
run:

1 2 3 4 5 6 7 

*/

 



answered Feb 12, 2019 by avibootz
0 votes
#include <iostream>
#include <vector>

using namespace std; 
  
class Test { 
    vector<int> vec; 
  
public: 
    Test(vector<int> v) : vec(v) { } 
    void print()  { 
        for (auto const& v : vec) cout << v << " ";
    } 
}; 
  
int main() 
{ 
    vector<int> vec; 
    
    for (int i = 1; i <= 10; i++) 
        vec.push_back(i); 
        
    Test obj(vec); 
    obj.print(); 
    
    return 0; 
} 


/*
run:

1 2 3 4 5 6 7 8 9 10 

*/

 



answered Feb 12, 2019 by avibootz

Related questions

1 answer 174 views
1 answer 88 views
88 views asked Dec 19, 2024 by avibootz
1 answer 160 views
1 answer 112 views
112 views asked Dec 6, 2020 by avibootz
3 answers 227 views
2 answers 168 views
168 views asked Feb 11, 2019 by avibootz
...