Проблема в моей функции C ++ с размером вектора не увеличивается - PullRequest
0 голосов
/ 04 апреля 2020

В следующем коде я пытаюсь добавить элементы к вектору строк, целых и двойных чисел, но когда я вывожу размер вектора, он никогда не переместится за 1. Это заставляет меня думать, что это не добавление элементов, а вместо этого изменить первый элемент?

// Need to show this for the code I'm having issues with
struct Store_Info{ // Stores all info for a given item
    string store_name;
    string location;
    // vector<string> = item | vector<int> = stock || vector<double> = price
    pair<pair<vector<string>, vector<int>>, vector<double>> item_stock_price;

    Store_Info() = default;
    Store_Info(string, string);

    string how_many(int);
};


void stock_info(vector<Store_Info> &stores, int n_stores){ // This is the code I need help with
    for (int i(0); i<n_stores; i++){
        string name; string loc;
        int counter(0);
        bool active(true);
        while(active){
            string line;
            std::getline (cin,line);
            if (line == "")
                active = false;
            else if (counter == 0){
                name = line;
                counter++;
            }
            else if (counter == 1){
                loc = line;
                stores[i] = Store_Info(name, loc);
                counter ++;
            }
            else{
                regex reg{R"((\w+),(\d+),\W(\d+.\d+))"}; // From professor's piazza post

                std::smatch m;
                std::regex_match(line, m, reg);
                Store_Info current_store = stores[i];
                pair itemStock = std::get<0>(current_store.item_stock_price);

                std::get<0>(itemStock).push_back(m[1].str()); // Defines item name
                std::get<1>(itemStock).push_back(std::stoi(m[2].str())); // Defines amount in stock
                std::get<1>(current_store.item_stock_price).push_back(std::stod(m[3].str())); // Defines price
                //cout << std::get<1>(current_store.item_stock_price).capacity();
            }
        }
    }
}

Извините, если он плохо отформатирован, это мой первый пост. Любая помощь приветствуется, спасибо!

edit: Может быть полезно знать, что вводится ..
Используя стандартный ввод, функция читает это:
(int) Магазины:
(Название магазина)
(Местоположение)
(наименование товара), (количество), $ (цена)

Пример.
2 Магазины:
Местный продуктовый магазин
Калифорния
Яблоки, 2, $ 1,20

Молл
Мичиган
Пицца, 3, $ 4,00
Торт, 1, $ 10,45

1 Ответ

1 голос
/ 04 апреля 2020

Пожалуйста, рассмотрите возможность изменить свой код на что-то вроде этого. Использование вложенной пары слишком запутанно. Тогда хотя бы используйте std :: tuple. Также вам нужно использовать ссылку на структуру, а не ее копию!

struct Item {
    string name; // Defines item name
    int amount; // Defines amount in stock
    double price; // Defines price
}

struct Store_Info { // Stores all info for a given item
    string store_name;
    string location;
    // vector<string> = item | vector<int> = stock | vector<double> = price
    vector<Item> items;

    Store_Info() = default;
    Store_Info(string, string);

    string how_many(int);
};

void stock_info(vector<Store_Info> &stores, int n_stores){ // This is the code I need help with
    for (int i(0); i<n_stores; i++){
        string name; string loc;
        int counter(0);
        bool active(true);
        while(active){
            string line;
            std::getline (cin,line);
            if (line == "")
                active = false;
            else if (counter == 0){
                name = line;
                counter++;
            }
            else if (counter == 1){
                loc = line;
                stores[i] = Store_Info(name, loc);
                counter ++;
            }
            else{
                regex reg{R"((\w+),(\d+),\W(\d+.\d+))"}; // From professor's piazza post

                std::smatch m;
                std::regex_match(line, m, reg);
                Store_Info &current_store = stores[i]; // need to be reference and not the copy !

                //                               item name |  amount               |  price
                current_store.items.emplace_back(m[1].str(), std::stoi(m[2].str()), std::stod(m[3].str()));
            }
        }
    }
}

Не уверен насчет других ошибок или проблем, потому что этот код не работает.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...