C++ ssd5 25 optional exercise 6
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++ ssd5 25 optional exercise 6相关的知识,希望对你有一定的参考价值。
// parts.h
#ifndef _PARTS_H_
#define _PARTS_H_
#include <vector>
#include <map>
#include <string>
#include <iostream>
using namespace std;
//**************** Part ****************
class Part {
private:
static int count;
public:
string name;
map<string, int> subparts;
// TODO: Finish declaration
Part(string const &n) : name(n),subparts(){};
void describe(void);
int count_howmany(Part const *p);
};
//**************** NameContainer ****************
class NameContainer {
private:
map<string, Part*> name_map;
public:
NameContainer(void) {};
Part* lookup(string const &name) {
// TODO: Finish implementation
Part *pt = new Part(name);
name_map.insert(pair<string, Part*>(name,pt));//如果存在则第二次会插入失败,确保不会产生两个相同的PArt对象
map<string, Part*>::iterator iter;
iter = name_map.find(name);
return iter->second;
}
};
NameContainer partContainer;
//**************** Part Member Functions ****************
void Part::describe(void) {
// TODO: Finish implementation
cout << "part " << this->name << " subparts are :" << endl;
map<string, int>::iterator iter;
for (iter = subparts.begin(); iter != subparts.end(); iter++)//iterator to traverse
{
cout << iter->first << " " << iter->second << endl;
}
}
int Part::count = 1;
int Part::count_howmany(Part const *p) {
// TODO: Finish implementation
if (this->name == p->name)
return 1;
else
{
int total = 0;
map<string, int>::iterator iter;
for (iter = subparts.begin(); iter != subparts.end(); iter++)//遍历,此处是按字母升序完成
{
Part * pt = partContainer.lookup(iter->first);
total += pt->count_howmany(p)*iter->second;//注意+=号而不是等号,如果是等号则是替换;
}
return total;
}
/*int num;
if (p->name == this->name)
return 0;
else
{
map<string, int>::iterator iter;
for (iter = subparts.begin(); iter != subparts.end(); iter++)
{
Part * pt = partContainer.lookup(iter->first);
if (pt->subparts.empty() && iter->first != p->name)
continue;
count = count*(iter->second);
pt->count_howmany(p);
}
num = count;
}
return num;
*/
}
//**************** Miscellaneous Functions ****************
void add_part(string const &x, int q, string const &y) {
// TODO: Finish implementation
Part* xp = partContainer.lookup(x);
xp->subparts.insert(pair<string, int>(y,q));
}
#endif
#pragma once
以上是关于C++ ssd5 25 optional exercise 6的主要内容,如果未能解决你的问题,请参考以下文章
C++ ssd5 12 optional exercise2
James Munkres Topology: Sec 22 Exer 3
James Munkres Topology: Sec 18 Exer 12