ZBLOG

使用其他方法实现此代码:#ifndef NULL #define NULL 0 #endif #include #include #include using namespace std; struct LNode { //存储数据 int month; int day; string name; double price; LNode* next;//后继指针 LNode() {}; LNode(int a, int...

下面是使用C++11标准的另一种实现方式:

#include #include #include #include // 使用智能指针

using namespace std;

struct LNode {

int month;
int day;
string name;
double price;
shared_ptr<LNode> next; // 使用智能指针

};

class List { private:

shared_ptr<LNode> head;
int size;

public:

List() : head(nullptr), size(0) {}

void insert(int a, int b, const string& c, double d)
{
    shared_ptr<LNode> newNode = make_shared<LNode>();
    newNode->month = a;
    newNode->day = b;
    newNode->name = c;
    newNode->price = d;
    newNode->next = nullptr;

    if (head == nullptr)
    {
        head = newNode;
    }
    else
    {
        shared_ptr<LNode> p = head;
        while (p->next != nullptr)
        {
            p = p->next;
        }
        p->next = newNode;
    }

    size++;
}

double getAveragePrice(const string& itemName, int count)
{
    double sum = 0.0;

	shared_ptr<LNode> p = head;

	for (int i = 0; i < size && count > 0; i++)
	{
		if (p && p->name == itemName)
		{
			sum += p->price;
			count--;
		}

		p = p->next;
	}

	return sum / count; 
}

};

int main() {

int m, n;

cin >> m >> n;

List L1;

for (int i = 0; i < m; i++)
{
	string str;
	cin >> str;

	int a = stoi(str.substr(0, 2));
	int b = stoi(str.substr(3, 2));

	string c;
	double d;

	cin >> c >> d;

	L1.insert(a, b, c, d);
}

double ave1 = L1.getAveragePrice("keyboard", n);
double ave2 = L1.getAveragePrice("mouse", n);

cout << fixed << setprecision(1) << ave1 << endl;
cout << fixed << setprecision(1) << ave2 << endl;

return 0;

}


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=9597

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?