Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 10

1 Tutorial on C++ STL Map (ordered associative container) – pages 1-4

1 #include <stdio.h>
2 #include <iostream>
3 #include <string>
4 #include <map>
5 using namespace std;
6
7 int main(int argc, char *argv[])
8 {
9 map<string, int> numbers;
10
11 numbers.insert(pair<string,int>("One",1));
12 numbers.insert(pair<string,int>("Two",2));
13 numbers.insert(pair<string,int>("Three",3));
14
15 numbers["Six"] = 6; // Add new entry
16 numbers["Seven"] = 7;
17 numbers["Eight"] = 8;
18
19 numbers["Three"] = 333; // or to update
20
21 string findKey ("Three");
22 string findValue;
23
24 map<string, int>::iterator it = numbers.find(findKey);
25
26 if(it!=numbers.end())
27 printf("The number for %s is %d\n", findKey.c_str(), (*it).second);
28 else
29 printf("Error, the number for %s is not found\n", findKey.c_str());
30 cout << "\n";
31
32
33 for(map<string, int>::iterator iter=numbers.begin();
34 iter != numbers.end(); iter++) {
35 cout << iter->first << " => " << iter->second << '\n';
36 }
37 cout << "\n";
38
39 for(auto iterator = numbers.begin(); iterator != numbers.end(); iterator++){
40 cout << iterator->first << " => " << iterator->second << '\n';
41 }
42 }
43 Process started >>>
44 The number for Three is 333
45
46 Eight => 8
47 One => 1
48 Seven => 7
49 Six => 6
50 Three => 333
51 Two => 2
52
53 Eight => 8
54 One => 1
55 Seven => 7
56 Six => 6
57 Three => 333
58 Two => 2
59 <<< Process finished.

2 1
1 Tutorial on C++ STL Map (ordered associative container) – pages 1-4

1 http://en.wikipedia.org/wiki/Associative_containers

2 In the above example, six elements are entered using the insertion function, and then the first
3 element is deleted. Then, the size of the map is output. Next, the user is prompted for a key to
4 search for. Using the iterator, the find function searches for an element with the given key. If it
5 finds the key, the program prints the element's value. If it does not find it, an iterator to the end
6 of the map is returned and it outputs that the key could not be found. Finally all the elements in
7 the tree are erased.

8 Iterators

9 Maps may use iterators to point to specific elements in the container. An iterator can access both
10 the key and the mapped value of an element:[1]

11 map<Key,T>::iterator it; // declares a map iterator


12 it->first; // the key value
13 it->second; // the mapped value
14 (*it); // the "element value", which is of type: pair<const Key,T>

15 Below is an example of looping through a map to display all keys and values using iterators:

16 #include <iostream>
17 #include <string>
18 #include <map>
19
20 int main()
21 {
22 std::map <std::string, int> data{
23 { "Bobs score", 10 },
24 { "Martys score", 15 },
25 { "Mehmets score", 34 },
26 { "Rockys score", 22 },
27 { "Rockys score", 23 } /*overwrites the 22 as keys are identical */
28 };
29
30 // Iterate over the map and print out all key/value pairs.
31 for (const auto& element : data)
32 {
33 std::cout << "Who(key = first): " << element.first;
34 std::cout << " Score(value = second): " << element.second << '\n';
35 }
36
37 return 0;
38 }

39 This will output the keys and values of the entire map, sorted by keys.

2 2
1 Tutorial on C++ STL Map (ordered associative container) – pages 1-4

1 http://en.wikipedia.org/wiki/Associative_containers

2 The following example illustrates inserting elements into a map using the insert function and
3 searching for a key using a map iterator and the find function:

4 #include <iostream>
5 #include <map>
6 #include <utility> // make_pair
7
8 int main()
9 {
10 typedef std::map<char, int> MapType;
11 MapType my_map;
12
13 // insert elements using insert function
14 my_map.insert(std::pair<char, int>('a', 1));
15 my_map.insert(std::pair<char, int>('b', 2));
16 my_map.insert(std::pair<char, int>('c', 3));
17 my_map.insert(MapType::value_type('d', 4));
18 // all standard containers provide this typedef
19 my_map.insert(std::make_pair('e', 5));
20 // can also use the utility function make_pair
21 my_map.insert({'f', 6}); // using C++11 initializer list
22
23 // map keys are sorted automatically from lower to higher.
24 // So, my_map.begin() points to the lowest key value not the key
25 // which was inserted first.
26
27 MapType::iterator iter = my_map.begin();
28
29 // erase the first element using the erase function
30 my_map.erase(iter);
31
32 // output the size of the map
33 std::cout << "Size of my_map: " << my_map.size() << '\n';
34
35 std::cout << "Enter a key to search for: ";
36 char c;
37 std::cin >> c;
38
39 // find will return an iterator to the matching element if it is found
40 // or to the end of the map if the key is not found
41
42 iter = my_map.find(c);
43 if (iter != my_map.end() )
44 std::cout << "Value is: " << iter->second << '\n';
45 else
46 std::cout << "Key is not in my_map" << '\n';
47
48 // clear the entries in the map
49 my_map.clear();
50 }

51

2 3
1 Tutorial on C++ STL Map (ordered associative container) – pages 1-4

1 http://www.cplusplus.com/reference/map/map/map/

2 Example
1 // constructing maps
2 #include <iostream>
3 #include <map>
4
5 bool fncomp (char lhs, char rhs) {return lhs<rhs;}
6
7 struct classcomp {
8 bool operator() (const char& lhs, const char& rhs) const
9 {return lhs<rhs;}
10 };
11
12 int main ()
13 {
14 std::map<char,int> first;
15
16 first['a']=10;
17 first['b']=30;
18 first['c']=50;
19 first['d']=70;
20
21 std::map<char,int> second (first.begin(),first.end());
22
23 std::map<char,int> third (second);
24
25 std::map<char,int,classcomp> fourth; // class as Compare
26
27 bool(*fn_pt)(char,char) = fncomp;
28 std::map<char,int,bool(*)(char,char)> fifth (fn_pt);
29 // function pointer as Compare
30
31 return 0;
}
3
4
5 The code does not produce any output, but demonstrates some ways in which a map container can be
6 constructed.

2 4
1 Tutorial on C++ STL Map (ordered associative container) – pages 1-4

1 http://en.wikipedia.org/wiki/Unordered_associative_containers_(C%2B%2B)

2 Usage example
3 #include <iostream>
4 #include <string>
5 #include <unordered_map>
6
7 int main()
8 {
9 std::unordered_map<std::string, int> months;
10
11 months["january"] = 31;
12 months["february"] = 28;
13 months["march"] = 31;
14 months["april"] = 30;
15 months["may"] = 31;
16 months["june"] = 30;
17 months["july"] = 31;
18 months["august"] = 31;
19 months["september"] = 30;
20 months["october"] = 31;
21 months["november"] = 30;
22 months["december"] = 31;
23
24 std::cout << "september -> " << months["september"] << std::endl;
25 std::cout << "april -> " << months["april"] << std::endl;
26 std::cout << "december -> " << months["december"] << std::endl;
27 std::cout << "february -> " << months["february"] << std::endl;
28
29 return 0;
30
31 }

2 5
1 Tutorial on C++ STL Map (ordered associative container) – pages 1-4

1 http://en.wikipedia.org/wiki/Associative_containers

2 Usage
3 The following code demonstrates how to use the map<string, int> to count occurrences of
4 words. It uses the word as the key and the count as the value.

5 #include <iostream>
6 #include <string>
7 #include <map>
8
9 int main()
10 {
11 std::map<std::string, int> wordcounts;
12 std::string s;
13
14 while (std::cin >> s && s != "end")
15 ++wordcounts[s];
16
17 while (std::cin >> s && s != "end")
18 std::cout << s << ' ' << wordcounts[s] << '\n';
19 }

20 When executed, the user first types a series of words separated by spaces, and a word "end" to
21 signify the end of input; then the user can input words to query how many times each word
22 occurred in the previous series.

23 The above example also demonstrates that the operator [] inserts new objects (using the default
24 constructor) in the map if there isn't one associated with the key. So integral types are zero-
25 initialized, strings are initialized to empty strings, etc.

2 6
1 Tutorial on C++ STL Map (ordered associative container) – pages 1-4

1 http://en.wikipedia.org/wiki/Associative_containers

2 The following example illustrates inserting elements into a map using the insert function and
3 searching for a key using a map iterator and the find function:

4 #include <iostream>
5 #include <map>
6 #include <utility> // make_pair
7
8 int main()
9 {
10 typedef std::map<char, int> MapType;
11 MapType my_map;
12
13 // insert elements using insert function
14 my_map.insert(std::pair<char, int>('a', 1));
15 my_map.insert(std::pair<char, int>('b', 2));
16 my_map.insert(std::pair<char, int>('c', 3));
17 my_map.insert(MapType::value_type('d', 4));
18 // all standard containers provide this typedef
19 my_map.insert(std::make_pair('e', 5));
20 // can also use the utility function make_pair
21 my_map.insert({'f', 6}); // using C++11 initializer list
22
23 // map keys are sorted automatically from lower to higher.
24 // So, my_map.begin() points to the lowest key value not the key
25 // which was inserted first.
26
27 MapType::iterator iter = my_map.begin();
28
29 // erase the first element using the erase function
30 my_map.erase(iter);
31
32 // output the size of the map
33 std::cout << "Size of my_map: " << my_map.size() << '\n';
34
35 std::cout << "Enter a key to search for: ";
36 char c;
37 std::cin >> c;
38
39 // find will return an iterator to the matching element if it is found
40 // or to the end of the map if the key is not found
41
42 iter = my_map.find(c);
43 if (iter != my_map.end() )
44 std::cout << "Value is: " << iter->second << '\n';
45 else
46 std::cout << "Key is not in my_map" << '\n';
47
48 // clear the entries in the map
49 my_map.clear();
50 }

2 7
1 Tutorial on C++ STL Map (ordered associative container) – pages 1-4

1 http://en.wikipedia.org/wiki/Associative_containers

2 In the above example, six elements are entered using the insertion function, and then the first
3 element is deleted. Then, the size of the map is output. Next, the user is prompted for a key to
4 search for. Using the iterator, the find function searches for an element with the given key. If it
5 finds the key, the program prints the element's value. If it does not find it, an iterator to the end
6 of the map is returned and it outputs that the key could not be found. Finally all the elements in
7 the tree are erased.

8 Iterators

9 Maps may use iterators to point to specific elements in the container. An iterator can access both
10 the key and the mapped value of an element:[1]

11 map<Key,T>::iterator it; // declares a map iterator


12 it->first; // the key value
13 it->second; // the mapped value
14 (*it); // the "element value", which is of type: pair<const Key,T>

15 Below is an example of looping through a map to display all keys and values using iterators:

16 #include <iostream>
17 #include <string>
18 #include <map>
19
20 int main()
21 {
22 std::map <std::string, int> data{
23 { "Bobs score", 10 },
24 { "Martys score", 15 },
25 { "Mehmets score", 34 },
26 { "Rockys score", 22 },
27 { "Rockys score", 23 } /*overwrites the 22 as keys are identical */
28 };
29
30 // Iterate over the map and print out all key/value pairs.
31 for (const auto& element : data)
32 {
33 std::cout << "Who(key = first): " << element.first;
34 std::cout << " Score(value = second): " << element.second << '\n';
35 }
36
37 return 0;
38 }

39 This will output the keys and values of the entire map, sorted by keys.

2 8
1 Tutorial on C++ STL Map (ordered associative container) – pages 1-4

1 http://www.cplusplus.com/reference/map/map/map/

2 Example
1 // constructing maps
2 #include <iostream>
3 #include <map>
4
5 bool fncomp (char lhs, char rhs) {return lhs<rhs;}
6
7 struct classcomp {
8 bool operator() (const char& lhs, const char& rhs) const
9 {return lhs<rhs;}
10 };
11
12 int main ()
13 {
14 std::map<char,int> first;
15
16 first['a']=10;
17 first['b']=30;
18 first['c']=50;
19 first['d']=70;
20
21 std::map<char,int> second (first.begin(),first.end());
22
23 std::map<char,int> third (second);
24
25 std::map<char,int,classcomp> fourth; // class as Compare
26
27 bool(*fn_pt)(char,char) = fncomp;
28 std::map<char,int,bool(*)(char,char)> fifth (fn_pt);
29 // function pointer as Compare
30
31 return 0;
}
3
4
5 The code does not produce any output, but demonstrates some ways in which a map container can be
6 constructed.

2 9
1 Tutorial on C++ STL Map (ordered associative container) – pages 1-4

1
2 #include <stdio.h>
3 #include <iostream>
4 #include <string>
5 #include <map>
6
7 int main(int argc, char *argv[])
8 {
9 std::map<std::string, int> numbers;
10
11 numbers.insert(std::pair<std::string,int>("One",1));
12 numbers.insert(std::pair<std::string,int>("Two",2));
13 numbers.insert(std::pair<std::string,int>("Three",3));
14
15 numbers["Six"] = 6; // Add new entry
16 numbers["Seven"] = 7;
17 numbers["Eight"] = 8;
18
19 numbers["Three"] = 333; // or to update
20
21 std::map<std::string, int>::iterator it=numbers.find("Three");
22 if(it!=numbers.end())
23 printf("The number for %s is %d\n", (*it).first, (*it).second);
24 else
25 printf("Error, the number for Three is not found\n");
26
27
28 for(std::map<std::string, int>::iterator iter=numbers.begin();
29 iter != numbers.end(); iter++)
30 {
31 std::cout << iter->first << " => " << iter->second << '\n';
32 }
33 std::cout << "\n";
34 for(auto iterator = numbers.begin(); iterator != numbers.end(); iterator++){
35 std::cout << iterator->first << " => " << iterator->second << '\n';
36 }
37 }
38
39 NPP_EXEC: "Execute Compiled File" "C:\cpp\example11"
40 Process started >>>
41
42 The number is 333
43 Eight => 8
44 One => 1
45 Seven => 7
46 Six => 6
47 Three => 333
48 Two => 2
49
50 Eight => 8
51 One => 1
52 Seven => 7
53 Six => 6
54 Three => 333
55 Two => 2
56 <<< Process finished.

2 10

You might also like