pranay_teja
10/6/2018 - 12:02 PM

Vectors-Syntax

#include <bits/stdc++.h>
using namespace std;

// #Vectors #BasicProblem
// https://www.studytonight.com/cpp/stl/stl-container-vector

void print(vector<int> a);
void print(vector< vector<int> > a);

int main() {

//================( Vector Initialization )====================
	vector<int> a1(5);   // creates [0,0,0,0,0] defalut values 0
	print(a1);
	a1.push_back(2); // adds an element at end
	print(a1);
	a1.push_back(3);
	print(a1);

// ==============( Vector insert )============================
	a1.insert(a1.begin()+2,5); // adds element 5 before index 2 of vector
	print(a1);

// =====================( Vector Popback )====================
	a1.pop_back();   // deletes an element at end
	print(a1);

// ==================( Vector erase )=========================
	a1.erase(a1.begin()+5); // a1.erase(a.begin()+i) deletes element at ith index
	print(a1);
	cout<<endl;
	a1.erase(a1.begin()+2,a1.begin()+5);    // [2,5) erases [2 to 4]
	print(a1);
	cout<<endl;

// =================( Vector with custom defalut values)================
	vector<int> a2(5,-4); // creates [-4,-4,-4,-4,-4] vector with 5 size and -4 as defalut values
	print(a2);
	cout<<endl;

// ===========================( Vector resize )=====================
	vector<int> a3;
	a3.resize(5);    // changes a3 into [0,0,0,0,0]
	print(a3);

	vector<int> a4;
	a4.resize(5,-4);    // changes a4 into [-4,-4,-4,-4,-4]
	print(a4);
	cout<<endl;

// ================( Multidimensional vector(Vector of 1-D vectors) )=============
	vector< vector<int> > a5;
	int rows=4,cols=5;  // rows-> number of 1-D Vectors; cols-> size of each 1-D Vector
	a5.resize(rows);

    // ==============( ** IMP **)======================
	// (OR) it can be initialized as
	// vector< vector<int> > a5(rows,vector<int>(cols))

	for(int i=0;i<rows;i++){
	    a5[i].resize(cols);
	}
	cout<<a5[0][1]<<endl;    // now vector can an accessed normally using rows and cols
	print(a5);

//=======================( make a copy)===================================
	vector<int> v1={1,2,3,4,5,6};
	vector<int> v2(v1.begin(), v1.begin()+4); //[0,4)
	cout<<"v2 copied 4 elems from v1"<<endl;
	for(auto i: v2){
		cout<<i<<" ";
	}
	cout<<endl;

	return 0;
}

void print(vector<int> a){
    for(int i=0;i<a.size();i++){
        cout<<a[i]<<" ";
    }
    cout<<endl;
}

void print(vector< vector<int> > a){
    for(int i=0;i<a.size();i++){
        for(int j=0;j<a[i].size();j++){
            cout<<a[i][j]<<" ";
        }
        cout<<endl;
    }
}