c++ vector size initialization code example

Example 1: initialize 2d vector of ints c++

auto M = 4;	// num of rows
auto N = 3; // num of cols in each row
auto default_value = 1; // default value of all int elements
std::vector<std::vector<int>> matrix(M, std::vector<int>(N, default_value));

Example 2: how to create a vector in c++

// CPP program to create an empty vector 
// and push values one by one. 
#include <vector>

using namespace std;
int main() 
{ 
    // Create an empty vector 
    vector<int> vect;  
    //add/push an integer to the end of the vector
    vect.push_back(10); 
	//to traverse and print the vector from start to finish
    for (int x : vect) 
        cout << x << " ";

    return 0; 
}

Example 3: how to initialize vector in c++ with all elements 0

vector<int> arr(10,0);

Example 4: c++ vector size

#include <vector>

int main() {
  std::vector<int> myVector = { 666, 1337, 420 };
  
  size_t size = myVector.size(); // 3
  
  myVector.push_back(399); // Add 399 to the end of the vector
  
  size = myVector.size(); // 4
}

Example 5: c++ create vector of size

// create a vector with 20 integer elements
std::vector<int> arr(20);

for(int x = 0; x < 20; ++x)
   arr[x] = x;

Example 6: declare vector of size n in c++

#include <vector>

auto n = 20
// create a vector with n=20 integer elements
std::vector<int> arr(n);