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 180 views
1 answer 98 views
98 views asked Dec 19, 2024 by avibootz
1 answer 174 views
1 answer 125 views
125 views asked Dec 6, 2020 by avibootz
3 answers 242 views
2 answers 181 views
181 views asked Feb 11, 2019 by avibootz
...