Quantcast
Viewing all articles
Browse latest Browse all 4

C++ maps: an exercise

Why doesn’t the following code compile? Without changing the definition of the struct Employee, can you make it compile so that it does what it’s meant to do?

#include <iostream>
#include <map>
#include <string>
 
using namespace std;
 
struct Employee
{
	string name;
	Employee(const string& s) : name(s) { }
};
 
int main()
{
	map<int, Employee> id;
	id[0] = Employee("John Smith");
	id[1] = Employee("Mary Jane");
	cout << id[0].name << endl;
 
	map<Employee, int> id2;
	Employee a("A"), b("B");
	id2[a] = 100;
	id2[b] = 200;
	return 0;
}

Answers here.

(I gave this exercise to my C++ students a couple of weeks ago.)


Viewing all articles
Browse latest Browse all 4

Trending Articles