Trying to print multiple statuses using classes.

closed account (zbX9z8AR)
What is supposed to happen is that the user should type in an integer. It should print that amount of statuses, but I'm wondering if I messed up in any of the classes, loops, etc.


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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <map>
#include <fstream>
using namespace std;

class Person{
private:
	char hStatus;
public:
	Person(char status);
	char getStatus();
	char setStatus(char newStatus);
};

Person::Person(char status)
{
	hStatus = status;
}

char Person::getStatus()
{
	return hStatus;
}

char Person::setStatus(char newStatus)
{
	hStatus = '0';
	hStatus = newStatus;
}

class Islands{
public:
	std::map<int, Person*> iCollect;
	std::map<int, Person*>::iterator pit;
	void addIsland();
	void printStatus();
};


void Islands::addIsland()
{
	char status = 'h';
	Person *iMember = 0;
	iMember = new Person(status);
	iCollect.insert(make_pair(status, iMember));
}

void Islands::printStatus()
{
	for(pit = iCollect.begin(); pit != iCollect.end(); pit++)
	{
		cout << "Status: " << pit->second->getStatus() << endl;
	}
}

int main()
{
	Islands island_catalog;
	int num = 0;
	cout << "How many islands?\n";
	cin >> num;
	for(int i=0; i<num; i++)
	{
		island_catalog.addIsland();
	}
	island_catalog.printStatus();
	return 0;
}


addIsland() is only ever going to add one island.

Line 44: status is always 'h'.
Line 47: A std::map can only have only entry with a specific key. Your first insert will work. Subsequent inserts will fail since an entry with status 'h' already exists.

If you want to create multiple islands with the same status, use std::multimap which allows duplicate keys.

Topic archived. No new replies allowed.