How to insert data in the map of strings?
Last Updated :
14 Dec, 2020
Maps are associative containers that store elements in a specific order. It stores elements in a combination of key values and mapped values.
Syntax:
map<data type of key, data type of value> M
To use the above syntax for the map in C++, it is important to include the below header file:
Header File:
#include <map>
To insert the data in the map insert() function in the map is used. It is used to insert elements with a particular key in the map container.
Syntax:
iterator map_name.insert({key, element})
Parameters: It accepts a pair that consists of a key and element which is to be inserted into the map container but it only inserts the unique key. This means that the function does not insert the key and element in the map if the key already exists in the map.
Return Value: It returns an iterator pointing to the new element in the map.
Below is the program to illustrate the same:
C++
#include <iostream>
#include <map>
using namespace std;
int main()
{
string s = "abc" ;
string s1 = "bca" ;
string s2 = "cba" ;
map<string, string> m;
m.insert(pair<string, string>(s1, s));
m.insert(pair<string, string>(s, s2));
for ( auto itr = m.begin();
itr != m.end(); ++itr) {
cout << itr->first << '\t'
<< itr->second << '\n' ;
}
return 0;
}
|
There is another way to store the data in the map, below is the syntax for the same:
Syntax:
iterator map_name.insert(iterator position, {key, element})
Parameters: The function accepts two parameters which are described below:
- {key, element}: This specifies a pair that consists of a key and element which is to be inserted into the map container.
- position: It only points to a position from where the searching operation for insertion is to be started to make the process faster. The insertion is done according to the order which is followed by the container.
Return Value: The function returns an iterator pointing to the new element in the container.
Below is the program to illustrate the same:
C++
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<string, int > mp;
mp.insert({ "abc" , 30 });
mp.insert({ "bcd" , 40 });
auto it = mp.find( "bcd" );
mp.insert(it, { "dcd" , 60 });
cout << "KEY\tELEMENT\n" ;
for ( auto itr = mp.begin();
itr != mp.end(); ++itr) {
cout << itr->first << '\t'
<< itr->second << '\n' ;
}
return 0;
}
|
Output:
KEY ELEMENT
abc 30
bcd 40
dcd 60
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...