带有自定义类的矢量的矢量
Vector of Vector with custom class
本文关键字:自定义 更新时间:2023-10-16
我试图自学C++,并在网上发现了一个面向苏打水库存的示例问题。 我有两类 1) 库存和 2) 苏打水。 苏打水包含其初始量 (int)、名称(字符串)、id(字符串)和数量 (int)。 库存包含矢量(苏打类型)的矢量。
库存的类别声明:
private:
std::vector< std::vector<Soda> > softDrinks;
public:
Inventory();
void buildInventoryGood();
void processTransactionsGood();
std::string displayReport();
苏打水类声明:
private:
std::string name;
std::string id;
int quantity;
int startingAmount;
int numberOfTransactions;
public:
Soda();
Soda(std::string sodaName, std::string sodaID, int initialAmount);
int addSoda(std::string id, int amount);
int withdrawSoda(std::string id, int toWithdraw);
std::string Report();
std::string getName();
std::string getID();
我可以运行buildInventoryGood(),它可以很好地构建一切。 (以下是我要做报告的结果)
Name ID InitialAmount FinalAmount
coke 123 100 300
pepsi 321 200 200
Shasta 987 300 300
我的问题是processTransactionGood()。 我在那里留下了一些cout调试语句来帮助我弄清楚发生了什么。
void Inventory::processTransactionsGood()
{
vector<Soda> vecSoda;
string textline;
string name;
string id;
int quantity;
ifstream infile("data6trans.txt");
while (getline(infile, textline))
{
string space_string;
std::istringstream text_stream(textline);
text_stream >> id;
getline(text_stream, space_string, ' '); // Read characters after number until space.
text_stream >> quantity;
for (auto drink : softDrinks) {
auto it = find_if(drink.begin(), drink.end(), [id](Soda obj) {return obj.getID() == id; });
if (it == drink.end()) {}
else {
auto index = distance(drink.begin(), it);
cout << id << " " << quantity << " " << index << "a" << endl;
drink[index].withdrawSoda(id, quantity);
cout << drink[index].Report() << endl;
}
}
}
}
最后一个cout语句向我显示处理了给定的苏打水(在这种情况下减去值为1)
Name Id starting final
Shasta 987 300 299
沙斯塔的最终结果应该是 299。 但是当我运行 displayReport() 时,我得到了一个我意想不到的结果:
string Inventory::displayReport()
{
string report = "NametIDtInitialAmounttFinalAmountn";
for (auto item : softDrinks) {
for (auto drink : item) {
report += drink.Report();
}
}
return report;
}
我得到:
Name ID InitialAmount FinalAmount
coke 123 100 300
pepsi 321 200 200
Shasta 987 300 300
总而言之:我不确定我是否掌握了向量向量的做法,并且我没有按照应有的
方式设置某些内容 编辑:^ 我不知道正确的方法是什么,正在寻找指针或引用。
for (auto drink : softDrinks)
使drink
成为softDrink
元素的副本。这就是为什么修改后的元素不会存储到softDrinks
.
请使用
for (auto &drink : softDrinks)
而不是手头有参考。
相关文章:
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 如何将点击的信号和插槽添加到qt中的自定义按钮中
- C++自定义比较函数
- 如何比较自定义类的std::变体
- std::设置自定义比较器
- 如何正确实现和访问运算符的各种自定义枚举器
- flutter:即使shouldRepaint()返回true,自定义画家也不会重新绘制
- 自定义先决条件对移动分配运算符有效吗
- 使用VS Code和CMake Tools运行自定义命令
- 如何创建从Maya(或类似程序)到虚幻引擎的自定义数据导出插件
- std::ranges::elements_view,用于自定义类似元组的数据
- 跟随整数索引列表的自定义类迭代器
- 参数化自定义CMake工具链
- 使用自定义比较函数使用std::sort()对矢量字符串进行排序时出现问题
- 如何在自定义类中启用'auto loops'?
- 使用QJsEngine在Qt中注册自定义类型
- Qt自定义QPush按钮未显示在布局上
- 自定义对象的dlib序列化在gcc中失败
- 自定义创建QFuture
- 如何在QT中的自定义视频小工具t上绘制矩形