Let's assume that I have a class named Store which contains products. Functions are inlined for simplicity.
class Store
{
public:
Store(string name)
: _name(name)
{}
string getName() const
{ return _name; };
const std::vector<string> getProducts()
{ return _products; };
void addProduct(const string& product)
{ _products.push_back(product); }
private:
const string _name;
std::vector<string> _products;
};
Then I have a two dimensional string array which contains store-product -pairs. Same store can be multiple times in array.
string storeListing[4][2] = {{"Lidl", "Meat"},
{"Walmart", "Milk"},
{"Lidl", "Milk"},
{"Walmart", "Biscuits"}};
Now I want to iterate through array, create Store-object for each store in array and add products of it to object. So I need to use existing Store-object or create a new if there is no any with correct name yet. What is a way to implement this? Currently I'm trying to use pointer and set it to relevant object, but I'm getting sometimes segmentation faults and sometimes other nasty problems when I modify code slightly. I guess I'm calling some undefined behavior here.
std::vector<Store> stores;
for (int i = 0; i < 4; ++i) {
string storeName = storeListing[i][0];
string productName = storeListing[i][1];
Store* storePtr = nullptr;
for (Store& store : stores) {
if (store.getName() == storeName) {
storePtr = &store;
}
}
if (storePtr == nullptr) {
Store newStore(storeName);
stores.push_back(newStore);
storePtr = &newStore;
}
storePtr->addProduct(productName);
}