- map :: insert( )
1.1 iterator map_name.insert({key, element})
// C++ program to illustrate
// map::insert({key, element})
#include <bits/stdc++.h>
using namespace std;
int main()
{
// initialize container
map<int, int> mp;
// insert elements in random order
mp.insert({ 2, 30 });
mp.insert({ 1, 40 });
mp.insert({ 3, 60 });
// does not inserts key 2 with element 20
mp.insert({ 2, 20 });
mp.insert({ 5, 50 });
// prints the elements
cout << "KEY\tELEMENT\n";
for (auto & itr : mp) {
cout << itr.first
<< '\t' << itr.second << '\n';
}
return 0;
}
====================================================================================================
KEY ELEMENT
1 40
2 30
3 60
5 50
1.2 iterator map_name.insert(iterator position, {key, element})
// C++ program to illustrate
// map::insert(iteratorposition, {key, element})
#include <bits/stdc++.h>
using namespace std;
int main()
{
// initialize container
map<int, int> mp;
// insert elements in random order
mp.insert({ 2, 30 });
mp.insert({ 1, 40 });
auto it = mp.find(2);
// inserts {3, 60} starting the search from
// position where 2 is present
mp.insert(it, { 3, 60 });
// prints the elements
cout << "KEY\tELEMENT\n";
for (auto itr = mp.begin(); itr != mp.end(); ++itr) {
cout << itr->first
<< '\t' << itr->second << '\n';
}
return 0;
}
==================================================================================================== KEY ELEMENT
1 40
2 30
3 60
1.3 iterator map_name.insert(iterator position1, iterator position2)
// C++ program to illustrate
// map::insert(iteratorposition1, iteratorposition2)
#include <bits/stdc++.h>
using namespace std;
int main()
{
// initialize container
map<int, int> mp, mp1;
// insert elements in random order
mp.insert({ 2, 30 });
mp.insert({ 1, 40 });
// inserts all elements in range
// [begin, end) in mp1
mp1.insert(mp.begin(), mp.end());
// prints the elements
cout << "Elements in mp1 are\n";
cout << "KEY\tELEMENT\n";
for (auto itr = mp1.begin(); itr != mp1.end(); ++itr) {
cout << itr->first
<< '\t' << itr->second << '\n';
}
return 0;
}
====================================================================================================
Elements in mp1 are
KEY ELEMENT
1 40
2 30