使用我的sales_data类编写一个简单的程序
Using my sales_data class to write a simple program
我正在完成下面一本书中的练习:
使用您的
sales_data
类编写一个程序,读取几个同一isbn的事务,并计算每个isbn的次数发生
我已经写过这样的程序,在这个程序中,我必须输入一个数字列表,然后打印出每个数字出现的次数。
这是我的类的定义,书中提供给我完成这个任务:
#ifndef SALES_DATA_H
#define SALES_DATA_H
#include <string>
struct Sales_data {
std::string bookNo;
unsigned units_sold = 0;
double revenue = 0;
};
#endif
这是程序应该接收到的输入:
0-201-78345 1-x 19.99 (ISBN, units_sold, price to book)
0-201-78345 1-x 19.99 (same ISBN)
2-201-78345-z 2 26.99
输出应该是:
0-201-78345 x-1 OCCURS 2 times
2-201-78345-z OCCURS 1 times
我的程序不是读取所有的isbn并打印计数器,而是只在isbn不同时打印计数器。
这是我的代码:
#include <iostream>
#include "Sales_data.h"
#include <string>
int main()
{
Sales_data currVal,val;
double price = 0;
if (std::cin >> currVal.bookNo >> currVal.units_sold >> price) {
int cnt = 1;
while (std::cin >> val.bookNo >> val.units_sold >> price) {
if (currVal.bookNo == val.bookNo)
++cnt;
else {
std::cout << currVal.bookNo << " occurs" << cnt << " times" << std::endl;
currVal = val;
cnt = 1;
}//end of else
}//end of while
std::cout << currVal.bookNo << " occurs" << cnt << " times" << std::endl;
}// end of outhermost if
system("pause");
}
而且,如果不插入文件结束符的序列,我的程序不会打印最后一个ISBN。
尝试使用std::map
:
typedef std::map<Sales_Data, unsigned int> Container_Type;
Container_Time inventory;
//...
Sales_Data item;
// Assume Sales_Data has overloaded operator>>.
while (std::cin >> item)
{
Container_Type::iterator iter = inventory.find(item);
if (iter != inventory.end())
{
iter->second++; // Increment the occurances.
}
else
{
// New item, add to container.
inventory[item] = 1;
}
}
上面的代码还假设Sales_Data
重载了operator==
和operator<
。
读取后,遍历容器,输出项及其出现次数。
相关文章:
- 在c++中用vector填充一个简单的动态数组
- 如何使用 samtools C API 构建一个简单的主.cpp文件
- 为什么一个简单的程序不能立即启动
- C++ - 在我尝试制作一个简单的计算器时有一个"uninitialized local variable y used"警告
- 为什么 MSVC C++编译器将一个简单的 Hello World 扩展为 4000 行汇编?
- 我写了一个简单的矢量程序,在其中我得到了以下输出。你能帮我理解它的输出吗?
- 如何使用 c++ 在命令行中创建一个简单的字符控制器?
- 对于 ~95% 写入/5% 读取线程安全的无序列图,有没有一个简单的解决方案?
- 在C++中创建一个简单的数据包路由器,如何跟踪"客户端"?
- 创建一个简单的前向迭代器,该迭代器在循环缓冲区的"end"处自动换行
- 我已经安装了用于c++编程的升华3,但在编写了一个简单的程序后,我遇到了以下错误
- 如何设置一个简单的CGAL+Qt程序
- 如何在一个简单的C++项目中使用Poco库
- 我创建了一个简单的程序,但有些地方不对劲
- Qt的新信号/时隙语法问题 - 连接到一个简单的函数
- 一个简单的 win32 多线程代码.这能行吗?
- 我正在尝试构建一个简单的程序来从 mysql 数据库中读取信息
- 创建一个简单的计算器,添加时遇到问题
- 我正在编写一个简单的客户端套接字应用程序,但在连接后服务器收到一个空缓冲区
- 为什么一个简单的"Hello World"风格的程序不能用Turbo C++编译?