簡體   English   中英

如何使用向量修改結構 c++

[英]How to use vector to modify a struct c++

嘿伙計們,這段代碼是用於咖啡機的。 我正在嘗試為這台機器添加操作員模式。

#include <iostream>
#include <string>
#include <iomanip>

using namespace std;

struct coffee {
  string name;
  int itemprice;
  string country;
  int quantity;

};

float remainder, price2, price;
int main() {
      int coffeetype = 1; 
    cout<<"\nPress'1'for buy a coffee\n";
    cout<<"\nPress' 2' for operator mode\n\n";
    int input;
    cin>>input;
    if (input==2)
    {
        cout << "Welcome to operator mode \n";
        cout << "Press '1' for add more coffee powder \n";
        cout << "Press '2' for exit\n";
        int op;
        cin >> op;
        if(op==2){
            return op;
        }
    }
        coffee drink[] = {
      { "Espresso", 120, "Italy", 20 },
      { "Iced coffee", 150, "France", 20 },
      { "Long black", 80, "Austral", 20 },
      { "Americano", 100, "America", 20 },
      { "Latte", 200, "Italy", 20 },
      { "Irishcoffee",130, "Ireland", 20 },
      { "Cappuccino", 180, "Italy", 20 }
    };

        cout << fixed;
        cout << setprecision(2);

   cout<<"Enter the name of coffee";



    while(coffeetype != 8){
    for (int i = 0; i != sizeof(drink)/sizeof(drink[0]); ++i)
        cout<< "\n " << i+1 << ") "<<drink[i].name<<"\t\t"<<drink[i].itemprice<<"\t\t"<<drink[i].country<<"\t\t("<<drink[i].quantity<<") remaining";

我已經為這個結構部分使用了一個向量。

vector<coffee> drink {
    { "Espresso", 120, "Italy", 20 },
    { "Iced coffee", 150, "France", 20 },
    { "Long black", 80, "Austral", 20 },
    { "Americano", 100, "America", 20 },
    { "Latte", 200, "Italy", 20 },
    { "Irishcoffee",130, "Ireland", 20 },
    { "Cappuccino", 180, "Italy", 20 }
};

但是在使用這部分后,我的“for循環”不起作用..有人可以幫我“計算”向量部分嗎?

我還需要您的幫助來制作操作員模式。通過操作員模式操作員應該能夠添加更多咖啡類型並更改機器中咖啡的數量。下面我展示了我從 stackoverflow 中的一位貢獻者那里獲得的代碼.但我不知道如何在我的代碼中實現以下代碼部分。

coffee entry;
cin >> entry.country
    >> entry.itemprice
    >> entry.country
    >> entry.quantity;
drink.push_back(entry);

如何使用上面的代碼修改 struct(drink) 中的細節。

首先, drink是一個糟糕的數組名稱選擇,它包含有關許多 dirnks 的信息 - 事實上,許多基於咖啡的飲料。 所以我們稱它為coffee_drinks

您的 for 循環的問題可能是您使用:

sizeof(drink)/sizeof(drink[0])

這個“hack”適用於 C 風格的 arrays - 不適用於std::vector s。 std::vectorsizeof()不是其元素的總大小(以字節為單位) - 因為元素的 memory 是在堆上動態分配的,並且僅由向量 class 實例指向

你可以寫:

for(int i = 0; i < coffee_drinks.size(); i++)

但更好的是,你可以做到:

for(coffee drink : coffee_drinks)

它遍歷std::vector中的所有元素。 此“技巧”適用於任何具有begin()end()成員的 class ; 它被稱為基於范圍的 for 循環

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM