C++ | Vector Initialization

Initialize vector from array

#include <iostream>
#include <vector>
using namespace std;

int main() {
  int arr[10] = {9, 9, 7, 9, 7, 8, 8, 7, 8, 0};
  vector<int> vec(arr, arr + 10);
  for (int item : vec)
    cout << item << " ";

  return 0;
}

Initialize from another vector

#include <iostream>
#include <vector>
using namespace std;

int main() {
  vector<int> vec1{9, 9, 7, 9, 7, 8, 8, 7, 8, 0};
  vector<int> vec2(vec1.begin(), vec1.end());

  for (int item : vec1)
    cout << item << " ";

  return 0;
}

Initialize in constructor

#include <iostream>
#include <vector>
using namespace std;

int main() {
  vector<int> vec{9, 9, 7, 9, 7, 8, 8, 7, 8, 0};

  for (int item : vec)
    cout << item << " ";

  return 0;
}

Initialize with default values

#include <iostream>
#include <vector>
using namespace std;

int main() {
  int n = 10;  // size of vector

  vector<int> vec(n, 99);

  for (int item : vec)
    cout << item << " ";

  return 0;
}

Populate empty vector

#include <iostream>
#include <vector>
using namespace std;

int main() {
  vector<int> vec;

  for (size_t i = 0; i < 10; i++)
    vec.push_back(10 + i);

  for (int item : vec)
    cout << item << " ";

  return 0;
}