Use of cin to enter value pairs into STL map

How do you write a function that reads value pairs from cin and places them in map msi?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
 //	C21Drill Map.cpp
#include <iostream>
#include <map>
#include <string>
#include <algorithm>
#include <iomanip>

// Write a function that reads value pairs from cin and places them in msi.
void fread(std::map<std::string, int>& pam);

int main()
{// Define a map<string,int> called msi and insert ten pairs into it.
	std::map<std::string, int> msi = {
		{ "lecture", 21 },
		{ "matinee", 53 },
		{ "musical", 24 },
		{ "broadway", 66 },
		{ "seminar", 12 },
		{ "panel", 37 },
		{ "ad hoc", 79 },
		{ "jury", 81 },
		{ "forum", 97 },
		{ "committee", 45 }
	};

	// Output the (name,value) pairs to cout in some format of your choice
	for (const auto& p : msi)
		std::cout << std::setw(10) << p.first << std::setw(5) << p.second << '\n';
	
	// Erase the (name, value) pairs from msi
	msi.clear();

	//	Read ten pairs from input and enter them into msi
	fread(std::map<std::string, int>& msi);


}


void fread(std::map<std::string, int>& pam) {
	for (std::string s; std::cin >> s;) {
		for (int n; std::cin >> n;)
			pam.emplace(s, n);
	}
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
std::map< std::string, int > read_map( std::istream& stm = std::cin )
{
    std::map< std::string, int > map ;
    std::string key ;
    int value ;

    // key does not contain white space
    while( stm >> key >> value ) map.emplace( key, value ) ;

    /*
    // key may contain white space
    while( std::getline( stm, key ) && // read a complete line as key (unformatted input)
           stm >> value && // read an int as value (formatted input)
           stm.ignore( 1000000, '\n' ) ) // extract and discard the trailing new line
    {
        map.emplace( key, value ) ;
    }
    */

    return map ;
}

http://coliru.stacked-crooked.com/a/d71da761e4a060fd
Registered users can post here. Sign in or register to post.