How to initialize a vector in C++

4 Answers

0 votes
#include <iostream>
#include <vector>
 
int main() {
    std::vector<int> vec{ 1, 1, 2, 3, 4, 4, 4, 5, 6, 6, 7, 7, 7, 7 }; 
  
    for (auto const& v : vec) {
        std::cout << v << " ";
    }
    
    std::cout << "\n";
    
    for (int i = 0; i < vec.size(); i++) {
        std::cout << vec[i] <<  " ";
    }
}
 
   
   
/*
run:
   
1 1 2 3 4 4 4 5 6 6 7 7 7 7 
1 1 2 3 4 4 4 5 6 6 7 7 7 7 
   
*/

 



answered Feb 18, 2019 by avibootz
edited Apr 17, 2024 by avibootz
0 votes
#include <iostream>
#include <vector>

int main() {
    std::vector<int> vec;  
      
    vec.push_back(23); 
    vec.push_back(6); 
    vec.push_back(-9); 
    vec.push_back(18); 
 
    for (auto const& v : vec) {
        std::cout << v << " ";
    }
}

  
  
/*
run:
  
23 6 -9 18 
  
*/

 



answered Feb 18, 2019 by avibootz
edited Apr 17, 2024 by avibootz
0 votes
#include <iostream>
#include <vector>

int main() {
    std::vector<int> vec(5, 9); 
 
    for (auto const& v : vec) {
        std::cout << v << " ";
    }
}

  
  
/*
run:
  
9 9 9 9 9 
  
*/

 



answered Feb 18, 2019 by avibootz
edited Apr 17, 2024 by avibootz
0 votes
#include <iostream>
#include <vector>

int main() {
    int arr[] = { 2, 1, 1, 4, 4, 4, 3, 5, 6, 6, 7, 7, 7, 7 };
    
    int len = sizeof(arr) / sizeof(arr[0]);
    std::vector<int> vec (arr, arr + len); 
     
    for (auto const& v : vec) {
        std::cout << v << " ";
    }
}
  
  
  
/*
run:
  
2 1 1 4 4 4 3 5 6 6 7 7 7 7 
  
*/

 



answered Feb 18, 2019 by avibootz
edited Apr 17, 2024 by avibootz
...