🎓 A1Learner
🔍
0 of 40 lessons completed

C++ Project: Store Inventory

A store inventory program lists the items in a store and counts the stock of each item. This program builds that list with a struct, a vector, a map, and a function.

The items in a vector

The Item struct holds a name and a price. The loop prints each item in the vector with its price.

#include <iostream>
#include <string>
#include <vector>

struct Item {
  std::string name;
  int price;
};

int main() {
  std::vector<Item> items = {{"Pen", 2}, {"Notebook", 5}, {"Ruler", 3}};
  for (Item item : items) {
    std::cout << item.name << " " << item.price << std::endl;
  }
  return 0;
}

The stock in a map

The stock map holds a count for each item name. The loop prints the counts in sorted order by name.

#include <iostream>
#include <map>
#include <string>

struct Item {
  std::string name;
  int price;
};

int main() {
  std::map<std::string, int> stock;
  stock["Pen"] = 12;
  stock["Ruler"] = 9;
  stock["Notebook"] = 7;
  for (auto pair : stock) {
    std::cout << pair.first << " " << pair.second << std::endl;
  }
  return 0;
}

Example

#include <iostream>
#include <map>
#include <string>
#include <vector>

struct Item {
  std::string name;
  int price;
};

int totalStock(std::map<std::string, int> stock) {
  int total = 0;
  for (auto pair : stock) {
    total += pair.second;
  }
  return total;
}

int main() {
  std::vector<Item> items = {{"Pen", 2}, {"Notebook", 5}, {"Ruler", 3}};
  for (Item item : items) {
    std::cout << item.name << " " << item.price << std::endl;
  }
  std::map<std::string, int> stock;
  stock["Pen"] = 12;
  stock["Ruler"] = 9;
  stock["Notebook"] = 7;
  for (auto pair : stock) {
    std::cout << pair.first << " " << pair.second << std::endl;
  }
  std::cout << "Total items: " << totalStock(stock) << std::endl;
  return 0;
}

Key points

  • An Item struct holds a name and a price for one item.
  • A std::vector<Item> holds the items in order.
  • A std::map<std::string, int> holds a stock count for each item name.
  • The totalStock function adds the stock counts in a map and returns the sum.
  • The program uses fixed data and reads no input.

In this example, the items vector prints each item with its price. The stock loop prints each count in sorted order by name. The totalStock function adds the counts, and the last line prints Total items: 28.

Note

The map prints its stock lines in sorted order by item name.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

In the capstone program, what does the totalStock function return?