You are on page 1of 12

C++ STL Map

Create:

 map<string ,int> map1;

 map<int,int> m{ {1,2} , {2,3} , {3,4} };

/* creates a map map2 which have entries copied from ap1.begin() to


map1.end() */
 map<char,int> map2 (map1.begin(), map1.end());

/* creates map map3 which is a copy of map m */


 map<char,int> map3 (m);

(insert):

 map1["abc"]=100;
 map1.insert(pair<int,int>(2, 30));
 m1.insert(make_pair(“Buet”, 10101478)); // not use insert() when use
// vector<> for multiple values.
// initialize container
map<int, int> mp1, mp2;
mp1.insert({ 1, 2 });

(access):

** Both at and [ ] are used for accessing the elements in the map.
The onlydifference:
(1) at throws an exception if the accessed key is not present(error দেখাবে)
(2) on the other hand operator [ ] inserts the key in the map if the key is not
present.

// prints value ssociated with key 1,


 cout << m.at(1) ;

// prints value associated with key 3


 cout << m[3] ;
(update):

m.at(1) = "vikas"; // changes the value associated with key 1 to vikas


m[2] = "navneet"; // changes the value associated with key 2 to navneet

/*since there is no key with value 4 in the map, it insert a key-value pair in map*/
 m[4] = "doodrah";

/* since there is no key with value 5 in the map,it throws an exception */


 m.at(5) = "umeshwa";

Functions:

empty(): returns boolean true if the map is empty.


size(): returns number of entries in the map.
max_size(): Returns the maximum number of elements that the map can hold.

begin(), end() and find() returns an iterator

pair insert(keyvalue, mapvalue) – Adds a new element to the map.

erase(iterator position) – Removes the element at the position pointed by the


iterator.

/*remove all elements up to element with key=3 in map1 */


 Map1.erase(m1.begin(), m1.find(3));

/*remove all elements with key = 4 */


int num;
 num = m1.erase(4);

erase(const g) – Removes the key value ‘g’ from the map.


clear() – Removes all the elements from the map.
m1.lower_bound(5); // it returns iterator
m1.upper_bound(5); // it returns iterator of sorted next pair.
member functions: (28 Functions)

 map::at
 map::begin
 map::cbegin
 map::cend
 map::clear
 map::count
 map::crbegin
 map::crend
 map::emplace
 map::emplace_hint
 map::empty
 map::end
 map::equal_range
 map::erase
 map::find
 map::get_allocator
 map::insert
 map::key_comp
 map::lower_bound
 map::max_size
 map::operator=
 map::operator[]
 map::rbegin
 map::rend
 map::size
 map::swap
 map::upper_bound
 map::value_comp

.begin(): This function returns an iterator which points to the first element
of the container. When the container has no values in it the iterator cannot be
dereferenced. The function accepts no parameter.
.end(): This function returns an iterator which points to the element which is
next to the last element of the container. The function accepts no
parameter.

cbegin(): map এর element গুলো সাজানো থাকে। সাজানোর পর, 1st element এর
address(iterator) return করে। The function does not accept any parameter.এটি
যে address return করবে সেই address দিয়ে 1st element কে modify করা যাবে না। শুধু
travel করা যাবে। The iterator returned is the constant iterator, they can’t be
used to modify the content. We can use them to traverse among the elements
of a map container by increasing ordecreasing the iterator.

cend(): same as cbegin() just from end element.

for (auto itr = mp.cbegin(); itr != mp.cend(); ++itr) {


cout << itr->first << itr->second <<endl;
}

crbegin(): প্রথমে map এর বৈশিষ্ট্য অনুযায়ী সব element sorted হবে। তারপর শেষ element কে
1st element ধরে তার address(iterator) return করবে। The function does not accept
any parameter.

crend(): same as crbegin() just from end element.

cout << "The max size of mp1 is " << m1.max_size();


Output:
The max size of m1 is 461168601842738790.
insert():The function accepts a pair that consists of a key and element which
is to be inserted into the map container. The function does not insert the key
and element in the map if the key already exists in the map.

map_name.insert({1,3} , {2,4} , {3,5});

// insert at ‘i’ position, after it’ll sorted.


 TP_Map.insert(i, { 5, 80 });

/* This variation inserts the entries in range defined by start_itr and end_itr of
another map. */
 insert(start_itr , end_itr);

 m.insert( pair<int,int> (4,5));


 m.insert( make_pair(5, 6));

// insert elements in random order


mp.insert({ 2, 30 });
mp.insert({ 1, 40 });
// does not inserts key 2 with element 20
mp.insert({ 2, 20 });

erase(): It used to erase keys, elements at any specified position or a given


range. The function accepts one mandatory parameter key which specifies the
key to be erased in the map container.
Return Value: The function returns 1 if the key element is found in the map
else returns 0. returns the number of deleted elements.
Syntax:
map_name.erase(iterator pos);
map_name.erase(key_type &k);
map_name.erase(iterator start, iterator end);

Example 1
// function to erase given keys
mp.erase(1);
mp.erase(2);
ymap.erase ('c'); // erasing by key
Example 2
//to erase the map values
auto var = TP_Map.find(1);
TP_Map.erase(var);

Example 3
mymap.erase (mymap.begin (),mymap.end ()); // erasing by range

Example 4
1 // erase all odd numbers from m
2 cout<<"After erasing odd numbers,elements are:\n ";
3 for(auto it = m.begin(); it != m.end(); )
4 if(it->first % 2 == 1)
5 it = m.erase(it);
6 else
7 ++it;

swap(): function is used to swap (or exchange) the contents of two maps but
both the maps must be of the same type although sizes may differ. Return
None.
1 map<char, int> m2;
2 m2.swap(m1); // all elements from m1 is copied and will store in m2(map).

clear(): function is used to remove all the elements of the map container. It
clears the map and sets its size to 0. No parameter, don’t return any value.
 mymap.clear();

// Conditional Clear
//**
1 cin>>n; // when n=1, delete map named “m1”
2 if(n==1){
3 m1.clear();
4 cout<<"\nGroup m1 has been cleared.";
5 }
6 else if(n==2){
7 m2.clear();
8 cout<<"\nGroup m2 has been cleared.";
9 }
10 else if(n==3){
11 m3.clear();
12 cout<<"\nGroup m3 has been cleared.";
13 }
14 else
15 cout<<"Invalid option!";

**/

emplace = প্রশস্ত করা।


emplace(): function is used to extend the map container by inserting new
elements into the container. Elements are built directly (neither copied nor
moved).
Parameter:The arguments forwarded to construct an element to be inserted into the
map.
Return value: It returns a bool pair that will indicate if the insertion is
occurred or not and returns an iterator pointing to the newly inserted element.

1 map<char, int> m;
2 m.emplace('a', 1);
3 m.emplace('b', 2);
4 m.emplace('c', 3);
5 m.emplace('d', 4);

/**
1 map<string, string> m;
2 // uses pair's move constructor
3 m.emplace(make_pair(string("a"), string("a")));
4 // uses pair's converting move constructor
5 m.emplace(make_pair("b", "abcd"));
**/
1 typedef map<string, int> city;
2 string name;
3 int age;
4 city fmly ;
5 int n;
6 cout<<"Enter the number of fmly members :";
7 cin>>n;
8 cout<<"Enter the name and age of each member: \n";
9 for(int i =0; i<n; i++)
10 {
11 cin>> name; // Get key
12 cin>> age; // Get value
13 //fmly[name] = age; // Put them in map
14 fmly.emplace(name,age);
15 }

emplace_hint(): function is used to extend the map container by inserting new


elements into the container using hint as a position for element. Elements are
built directly (neither copied nor moved). Insertion takes place only if the key is
not present already.

Syntax: iterator emplace_hint (const_iterator position, Args&&...args); //


since C++ 11

Return value: It returns an iterator to the newly inserted elements. If the


element already exists, insertion is failed and returns an iterator to the existing
element.

Example: 01
1 map<char, int> m = {
2 {'b', 20},
3 {'c', 30},
4 {'d', 40},
5 };
6 m.emplace_hint(m.end(), 'e', 50);
7 m.emplace_hint(m.begin(), 'a', 10);

Example: 02
 m1.emplace_hint(m1.end(), "Deep", "Engineering");
Example: 03
1 map<char,int> mymap;
2 auto it = mymap.end();
3 it = mymap.emplace_hint(it,'b',10);
4 mymap.emplace_hint(it,'a',12);
5 mymap.emplace_hint(mymap.end(),'c',14);

Example: 04
1 typedef map<string, int> city;
2 string name;
3 int age;
4 city fmly ;
5 int n;
6 cout<<"Enter the number of fmly members :";
7 cin>>n;
8 cout<<"Enter the name and age of each member: \n";
9 for(int i =0; i<n; i++)
10 {
11 cin>> name; // Get key
12 cin>> age; // Get value
13 fmly.emplace_hint(fmly.begin(),name,age);
14 }

Observers: পর্যবেক্ষক
key_comp():This function returns a copy of a key comparison object. This is by
default a less than object which works same like a less than operator <. The
object checks the order of the element keys in the map container. This
function takes the two arguments and checks its keys and returns true if the
first element is smaller and should go before the second element, else will
return false.
Parameters:
This function accepts no parameter.
Return value:
It returns a comparison object.
map<int, char> m1;
map<int, char>::key_compare cmp = m1.key_comp();
// Inserting elements
m1 [0] = 'a';
m1 [1] = 'b';
m1 [2] = 'c';
m1 [3] = 'd';
cout<<"Elements in the map are : \n";
int val = m1.rbegin()->first;
map<int, char>::iterator i = m1.begin();
do
{
cout << i->first << " : " << i->second<<'\n';
} while (cmp((*i++).first, val));

Object কে রিসিভ করার জন্য map<int, char>::key_compare


Var_Name=m1.key_comp();
মূলত ব্যবহার করতে হবে Var_Name(1st Parameter for key, 2nd Parameter for key);
unordered_multimap

member functions:

o unordered_multimap::begin
o unordered_multimap::bucket
o unordered_multimap::bucket_count
o unordered_multimap::bucket_size
o unordered_multimap::cbegin
o unordered_multimap::cend
o unordered_multimap::clear
o unordered_multimap::count
o unordered_multimap::emplace
o unordered_multimap::emplace_hint
o unordered_multimap::empty
o unordered_multimap::end
o unordered_multimap::equal_range
o unordered_multimap::erase
o unordered_multimap::find
o unordered_multimap::get_allocator
o unordered_multimap::hash_function
o unordered_multimap::insert
o unordered_multimap::key_eq
o unordered_multimap::load_factor
o unordered_multimap::max_bucket_count
o unordered_multimap::max_load_factor
o unordered_multimap::max_size
o unordered_multimap::operator=
o unordered_multimap::rehash
o unordered_multimap::reserve
o unordered_multimap::size
o unordered_multimap::swap
 non-member overloads:
o operators (unordered_multimap)
o swap (unordered_multimap)
Create:
 unordered_multimap <char, int> um;
 um c1;
c1.insert(um::value_type('a', 1));
 unordered_multimap<int, char> umm = {{5, ‘d’}};

insert:
umm.insert({1, ‘a’});
umm.insert(pair<int, char>(2, ‘b’ ));
umm.insert(make_pair(3, ‘c’));
umm.insert(make_pair(3, ‘c’));

You might also like