Stack array of structures - c++

I'm trying to figure our how implement an array of structures into stacks in this machine problem that i have. Here is the problem:
Make a program that will allow the user to perform the following activities stated below through array approach. Car Park Station offers 10 park lanes and each lanes can accommodate 5 cars.
a. Entry. It must be able to register new car and assign an available parking lane. Registration requires plate number, brand name, car color, owner and telephone number.
b. Release. It must be able to release car from an identified lane
c. Search. It must be able to identify the car location based on plate number.
d. Vacancy. It must be able to display available parking space.
From what i understand, i have to make a 2 dimensional array of structures containing various data types and i have to make a lifo code out of it. But my problem is, i know how to simulate an array approach lifo code with just a single data type but not with multiple data types. The part where i have to implement the 2 dimensional array of structure into a stack is where i got me stuck and confused. I've searched online to look for problems similar to mine but i couldn't find any. I tried to make a code shown below:
struct Car
{
string brand, color, owner;
int plate, phone;
};
class Stack
{
private:
Car * pointer = new Car[10][5];
int top;
public:
Stack() // Constructor
{...}
void Push(int plate, string brand, string color, string color, string owner, int number)
{...}
Pop()
{...}
}

Try to analyze your problem further before choosing an actual implementation solution (like 2-dim array).
In your task you have the following abstract entities:
CarParkStation with attributes: NumberOfParkLanes, which should be able to do something like: FindFreeLane, FindCar(plateNum), RegisterACar(car), ReleaseACar(car)
Lane with attributes: NumberOfPlaces, and with actions like: IsFull(), and maybe also: FindACar(plateNum), AddACar(car), RemoveACar(car)
Car with attributes: PlateNumber, Brand, Color, Owner, which should be able to do: GetPlateNumber(), and maybe also provide access to other parameters
Below is a very general example of possible CarParkStation class declaration:
class CarParkStation
{
public:
CarParkStation() = delete;
explicit CarParkStation(int numParkLanes);
~CarParkStation() = default;
std::shared_ptr<const Lane> FindFreeLane();
std::shared_ptr<const Car> FindCar(const PlateNumber& pNumber);
std::pair<std::shared_ptr<const Lane>, int position> FindWhereMyCarIsParked(const PlateNumber& pNumber);
bool RegisterACar(const Car& car);
bool ReleaseACar(const Car& car);
private:
std::vector<std::shared_ptr<const Lane> > lanes_;
std::set<std::shared_ptr<Car>, CustomCompareFunction > cars_;
};
Don't forget to write the tests along with your implementation. This will help you to verify your requirements and overall design. For example:
TEST_F(CarParkStationShould, returnCorrectFreeLane)
{
ASSERT_EQ(expectedFreeLane, carParkStation->FindFreeLane());
}
In general, focus on what should your application do first, and then think about how to implement it.

Related

Populating a vector of objects within a class

and I've hit my first wall on my coding project/assignment.
I'm to implement functionality into code that's been done to some stage, and I cannot alter the given code so I have to work around the given structure.
The code, in a nutshell, reads family relations from a text file and populates database with the family relation data and later on allows user to print out information he wants to access.
What I'm having trouble with is understanding how I can and how I have to utilize a struct given to me in the assignment. The struct is
struct Person
{
std::string id_ = NO_ID;
int height_ = NO_HEIGHT;
std::vector<Person*> parents_{nullptr, nullptr};
std::vector<Person*> children_;
};
and I'm using it at least in the initialization phase of the data structure.
I start by calling the process in main.cpp with
database->addRelation(it->child_, it->parents_, std::cout);
In the naming/height adding phase I'd simply do it with
MyPerson.id_ = id;
MyPerson.height_ = height;
where MyPerson is defined by Person MyPerson;
but as far as I can tell, I have to somehow access the object pointers to be able to populate the vectors for when I want to add children/parents to the person.
The class functions that are called when initializing person's name, height and family relations are these two:
void Familytree::addNewPerson(const string &id, const int &height, ostream &output)
{
MyPerson.id_ = id;
MyPerson.height_ = height;
}
void Familytree::addRelation(const string &child,
const std::vector<string>
&parents, ostream &output)
{
}
The addRelation fuction is what I'm having a hard time getting to work. Simply appending the strings to it won't work since it expects Person* -objects, which are, as far as I can tell, just pointers to the other Persons, but I'm not sure how I can access them.
Also, let me know if anything here is excessive or if I'm missing anything crucial, I'll edit it to the best of my ability
Editing with additional information:
The only things I've added myself that can be seen here is
Person MyPerson;
and the contents of the class function addNewPerson. The other snippets I can not change in any shape or form.
Edit#2
Current progress, debatable whether I'm closer or further from the goal
My persons map is using Personmap = std::map<std::string, Person >;
and I'm using it in addNewPerson with
persons_[id] = id;
persons_[id] = height;
, but I'm still randomly trying different things to try and make it work for the next phase where I need to somehow add the objects to the vectors.
The biggest problem I have is the fact that I do now know how to play around the difference of *Person and Person

Best data structure to use for playable regions in a game and how to change behaviour at runtime

I am making a Defcon inspired text based nuclear war game where you have to survive with the least casualties and you can upgrade your weapons and form alliances etc. In the game you can play as several regions e.g. Russia, USA, Europe. Each region has access to the same weapons and are exactly the same except that they have different values for the cost, range, number and damage of each of their weapons and need to be able to upgrade these variables as the game progresses.
At run-time the user will select the region that they play and the rest will be played by AI. AI-controlled regions every second have a random chance of upgrading their Weapon variables and the player can upgrade his own if he chooses to.
At the moment my weapon class looks like this:
class Weapon
{
private: // Weapon variables which every continent will have unique values for
int count;
int damage;
float cost;
int range;
public:
void upgradeRange(Weapon wep, float p) {
float percentDecimal = p / 100;
float modifier = percentDecimal + 1;
wep.range * modifier;
// more functions for upgrading each Weapon variable
// functions for setting and getting each weapon variable because they are private
}
};
And I have a WeaponArsenal Class where each weapon is defined: (at the moment each region class has its own WeaponArsenal object and therefore can define its own unique Weapon values).
class WeaponArsenal
{ /* Weapon Types */
public:
Weapon icbm; // intercontinental ballistic missile
Weapon mrbm; // medium range ballistic missile
Weapon srbm; // short range ballistic missile
Weapon bomb;
WeaponArsenal() {
// DEFAULT ICBM VALUES
icbm.setCount(0);
icbm.setCost(120);
icbm.setRange(8000);
icbm.setDamage(80);
// DEFAULT MRBM VALUES
mrbm.setCount(0);
mrbm.setCost(100);
mrbm.setRange(2000);
mrbm.setDamage(70);
// DEFAULT SRBM VALUES
srbm.setCount(0);
srbm.setCost(80);
srbm.setRange(800);
srbm.setDamage(55);
}
};
I now need to have each region stored in a data structure which allows their unique WeaponArsenal weapon values to be changed as the game develops without affecting the other regions. I want to know which data structure is best for this purpose because I think having a class for each region is very repetitive and not very easy to set at run-time.
I also would like to know how to change the player chosen region's weapon values at run-time without knowing which region he/she will chose. Should I make a pointer to this data structure that points to a different region at the start based on input? How do I allow the non player chosen regions which will be AI operated to call their AI functions? Could I use an EnemyRegion class with all common enemy region methods and if so how will I determine which continents should call these methods at run-time after the player has chosen their region.
I am reasonably new to C++ and have been told that I could use a map for each region from the standard library but I have no knowledge of the standard library and how I could apply maps for my specific uses. I would also still need to know about how the region behaviour can change at runtime.
The full code so far is available as a gist:
A simple solution would be to have a Region class containing a WeaponArsenal object.
class Region
{
public:
WeaponArsenal arsenal;
}
Then you could easily do what you described.
Region usa;
usa.arsenal.bomb.upgradeRange();
Also you shouldn't have to pass a Weapon object to the upgradeRange function.

Handling derived class creation using mappers in C++

I'm reading through Martin Fowler's PoEAA right now on object-relational structural patterns. As a project to do while learning them, I thought I'd build a mini eCommerce system in C++. I'm having trouble figuring out how to return the objects from the mapper.
I have a Product base class, which has derived classes Hat and Shirt. Products have a type member to identify which derived class they are. I also have a ProductMapper class, with derived classes HatMapper and ShirtMapper, all of which implement a bunch of finder methods which let me try and retrieve certain hats and shirts.
class Product
{
unsigned long long int id;
std::string name;
unsigned int type;
};
// Derived classes don't necessarily have the same members.
class Hat : public Product
{
unsigned char fitted;
unsigned char color;
unsigned char style;
};
class Shirt : public Product
{
unsigned char size;
};
In the logic part of my application where I'd instantiate these mappers and retrieve products is where I'm having trouble. I can instantiate a HatMapper and pull back Hat objects without any problem, same with a ShirtMapper and Shirt objects. The patterns work great in these cases (in particular I'm using class table inheritance, i.e. one product table with product data, one table for hats with hat-specific data, and one table for shirts with shirt-specific data).
My problem is, what do I do if I want to retrieve all products, both hats and shirts? I can instantiate a ProductMapper and fetch all of the product data, but that seems like the wrong approach since I'd have to loop through all the Products I retrieve and build up Hats and Shirts based on their type in my logic portion of the program. Additionally, I'd have to modify any code that handles the situation this way when I add new product types. Seems bad.
The Fowler book has examples of the mappers with the base mapper using the derived mappers which seems completely wrong to me (have to modify the base mapper every time I add a new product, not great). Here's a quick example of how it's done there:
class ProductMapper
{
unsigned long long int productId;
unsigned long long int productType;
HatMapper * hm;
ShirtMapper * sm;
Product * FindById(unsigned long long int id)
{
// Query database for data.
if (this->productType == PRODUCT_TYPE_HAT)
{
return hm->FindById(id); // Hat object.
}
else if (this->productType == PRODUCT_TYPE_SHIRT)
{
return sm->FindById(id); // Shirt object.
}
return NULL;
}
};
Here's how I'd use this in the logic part of my program. Examples of this aren't provided in the book:
ProductMapper * pm = new ProductMapper();
Product * p = pm->FindById(1); // It's a Product, but a Hat or Shirt?
// Have to check type since a Product was returned.
switch (p->type)
{
case PRODUCT_TYPE_HAT:
{
Hat * h = (Hat) p;
break;
}
// Etc. Modify this every time a new product type is added or removed.
}
This will introduce circular dependencies. Additionally, assuming I somehow eliminate the circular dependencies, the result of the HatMapper and ShirtMapper classes are Hat objects and Shirt objects. Thus when I return from the ProductMapper, I'll be downcasting, so I'd have to again manipulate the result in my logic, which again introduces the issue of modifying code when I introduce new product types.
I'm at a loss for what to do. In a perfect world, I'd like to have a Product class and a ProductMapper class, both of which I can extend quickly, introducing new product types without having to modify existing code (at least too much).
I would like to be able to use these patterns from PoEAA, they do seem nice and useful, but I'm not sure if it's just something I can't do in C++ or I'm missing something that's preventing me from doing it. Alternative patterns and approaches are also really welcomed.
It feels like the Type Object pattern could help in this case, I know the link is about game programming but it is sufficient to apply the pattern to other domains.
The problem right now is that if you want to add products you have to add several classes, which can become hard to maintain as you noticed.
Edit: Maybe you could use something like that (code is C++11 to simplify the example):
class ProductProperty
{
typedef std::map<std::string, unsigned char> PropertyMap;
PropertyMap properties;
public:
ProductProperty(std::initializer_list<PropertyMap::value_type> il):
properties(il)
{}
// Use of at() is intended to only deal with the defined properties
const PropertyMap::value_type::second_type&
get(const PropertyMap::value_type::first_type& prop) const
{
return properties.at(prop);
}
PropertyMap::value_type::second_type&
get(const PropertyMap::value_type::first_type& prop)
{
return properties.at(prop);
}
};
// Some helpers to illustrate
std::shared_ptr<ProductProperty> makeHatProperty()
{
return std::make_shared<ProductProperty>(
ProductProperty{
{"fitted", ***whatever**},
{"color", ***whatever**},
{"style", ***whatever**}
});
}
std::shared_ptr<ProductProperty> makeShirtProperty()
{
return std::make_shared<ProductProperty>(
ProductProperty{{"size", ***whatever**}}
);
}
class Product
{
unsigned long long int id;
std::string name;
unsigned int type;
std::shared_ptr<ProductProperty> properties;
public:
Product(std::shared_ptr<ProductProperty> props):
properties(props)
{}
// Whatever function you need to get/set/check properties
};

storing struct info in a vector (text rpg game)

I'm currently writing a text-based RPG for the Game Programming Institute course. I currently have a store in which the character can purchase armor, but now I need to add items to that. I have created a items class, but am having difficulty understanding how I can relate the store class, items class and player class together using a vector array.
I think what I should be doing is create a Item vector in the player class that holds information about the struct Items. Then when the player enters the store, the purchased items are entered into that vector.
I have included, what I feel are, relevant bits of my code. If anyone could give me some pointers or tips just to clear up my brain fog on understanding how to share information across these 3 classes that would be greatly appreciated.
Thanks!
Item.h
struct Item{
int itemType;
int goldValue;
};
In player.h class I have added the private data:
std::vector<Item> mItem;
In player.cpp I'm attemping to display the items with the function
void Player::purchaseItem(Item& mItems, int itemType, int itemValue)
Here is store.h
class Store{
public:
void enterStore(Player& player);
private:
Armor mStoreArmor;
int mCost;
};
A vector is designed to be a faster dynamically-allocated array.
I would think you'd want to use a hash or just a static array, with either keys or just indices, storing the quantity of each type of item.
you would obviously store possessions in a player class, and have the store class have a list of certain items (possibly with keys for what is in stock - this is why a hash would be a good idea).
When the player sees the store items and chooses one, the quantity in the player class's hash would be incremented.

List structure for c++ game

I'm making a very very basic game in C++ to gain some experience in the language and I have hit a bit of a brick wall in terms of progress.
My problem is, while I was designing a class for the player's weapons, I realized I required a list, as I will only have a certain number of weapons throughout the game.
So I ask you, if you were designing this, what implementation would you use for storing all of the weapons in a game? Why?
Here is my code so far for the weapons. as you can see I was just about to start defining all of them manually, starting with the "DoubleBlades"... (Edit* I forgot to note that players should be able to have more than one wepaon, and they can pick up more or drop some, so the list can grow and shrink)
#ifndef __WEAPON_H__
#define __WEAPON_H__
#include <string>
class Item
{
public:
Item(const std::string& name)
: name(name){ }
const std::string& getName(void) const { return name; }
int getID(void) const { return this->itemID;}
private:
std::string name;
int itemID;
};
class Weapon
: public Item
{
private:
int damage;
public:
Weapon(const std::string& name)
: Item(name) { }
virtual int getDamage(void) const = 0;
};
class DoubleBlades
: public Weapon
{
public:
DoubleBlades(int ammo)
: Weapon("DoubleBlades") { }
virtual int getDamage(void) const { return 12; }
};
#endif
Also if you spot any bad habits I would really appreciate letting me know.
I would use the standard implementation (std::list<Item*>) because it's easy to use ("out of the box") and, out of the standard containers, it seems to be most suitable:
You probably need support for fast adding/deleting of weapons (so no std::vector or C arrays)
You probably don't need support for fast searching of the list for a specific item (so no std::map)
BTW you need to have a virtual destructor in the Item class (this is a general rule on base classes in c++).
Oh, and another minor problem - i think the Weapon class does not need the damage member variable - the class doesn't use it and it has private access, so the deriving classes cannot use it either.
You might have to use dynamic_cast in your implementation - a virtual environment such as yours will probably require "safe" casting of pointers from Item* to Weapon*.
On a very basic level, you may not necessarily need a data structure. For instance, if you know exactly how many weapons, etc. you need/may possibly have, you can (wastefully) allocate an array of size n and have certain spots in the array as a pointer to a weapon (if you currently have that weapon, else NULL). Then, simply cast appropriately based on weapon index. But this is a naive approach. Otherwise, refer to Mike's comment above on the original post.
If the list is going to vary in size, I'd use either an std::vector or and std::set. With both, you'll get to use all the nice stl functions and what not. If you use set, it will be quicker to sort the "weapon objects". The vector is more useful if you want to know the order in which a particualr object was added.
If they are going to have a fixed number of weapons you can still use a vector or a set, just make sure you pass the exact size you're going to use to the constructors. This will allow for some optimizations like allocating contiguous blocks of memory (which speeds up access times).
You might actually look at std::map, -- consider something like
std::map<std::string, Item*>
This would allow you to access items by name, which can be nice syntactic sugar, and would allow you to quickly check for existence of an item using the count method.