带有自定义类的矢量的矢量

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)

而不是手头有参考。