pranay_teja
9/16/2018 - 5:52 AM

Maps Syntax

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

// #Hashing #Maps #BasicProblem
// https://www.studytonight.com/cpp/stl/stl-container-map

int main() {
	map< int, vector<int> > m;
	
	// =====( IMP )=====
	// use unordered_map if sorted order is not required
	
	m[-1].push_back(2);
	m[0].push_back(231);
	m[0].push_back(879);
	m[+1].push_back(567);
	
	// to use iterators in loops
	// https://www.geeksforgeeks.org/print-binary-tree-vertical-order-set-2/
	map< int, vector<int> > :: iterator i;
	for(i=m.begin();i!=m.end();i++){
	    for(int j=0;j<i->second.size();j++){    // i->second=m[i] (data)
	    	cout<< i->first <<" " << i->second[j] <<" ";	//i->first (key)
	    }
	    cout<<endl;
	}
//==================( .count(key) )=========================
    cout << m.count(0); // returns number of times 0 is present in hashmap
                        // so to check if a key is present or 
                        // .count() can be used
//==================( .erase(element) )===========================
    m.erase(1);
	
	map< int, int > m2;
	m2[-1]=11;
	// find.() function
	// http://www.cplusplus.com/reference/map/map/find/
	cout<<m2.find(-1)->second<<endl;    // m2.find(-1) returns iterator if found, else returns m2.end()
	                                    // iterator->second =m[iterator]
	map< int, int> m3;
	if(m3.empty()==true){
		cout<<"Empty!"<<endl;   // .empty() returns true if map is empty
	}
	if(m3.size()==0){
	    cout<<"Empty!"<<endl;   // .size() return size of map
	}
	                                  
	return 0;
}