c++ - 在 vector 中使用现有对象,如果 C++ 中不存在则创建新对象

标签 c++ pointers

假设我有一个名为 Store 的类,其中包含产品。为简单起见,函数是内联的。

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;
};

然后我有一个包含商店产品对的二维字符串数组。同一商店可以在数组中多次。

string storeListing[4][2] = {{"Lidl", "Meat"},
                             {"Walmart", "Milk"},
                             {"Lidl", "Milk"},
                             {"Walmart", "Biscuits"}};

现在我想遍历数组,为数组中的每个商店创建 Store-object,并将它的产品添加到对象。所以我需要使用现有的 Store-object 或创建一个新的(如果还没有任何具有正确名称的)。实现这个的方法是什么?目前我正在尝试使用指针并将其设置为相关对象,但是当我稍微修改代码时,有时会出现段错误,有时还会出现其他讨厌的问题。我想我在这里调用了一些未定义的行为。

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);
}

最佳答案

最有可能的是,因为您将“存储”拷贝插入到您的 vector 中:

if (storePtr == nullptr) {
    Store newStore(storeName);   //create Store on stack
    stores.push_back(newStore);  //Make a COPY that is inserted into the vec
    storePtr = &newStore;       // And this is where it all goes wrong.
}

newStore 在 if 结束时超出范围,StorePtr 丢失。

试试看:

storePtr = stores.back();

或者让你的载体成为std::vector<Store*> .

然后:

if (storePtr == nullptr) {
Store * newStore = new Store(storeName);   //create Store on stack
stores.push_back(newStore);  //Make a COPY that is inserted into the vec
storePtr = newStore;       // And this is where it all goes wrong.
}

当然,正如评论所建议的,std::map 更适合这里。

简而言之,std::map 存储键值对。关键很可能是您的商店名称和产品的值(value)。

简单示例:

std::map<std::string, std::string> myMap;
myMap["Lidl"] = "Milk";
myMap["Billa"] = "Butter";
//check if store is in map:
if(myMap.find("Billa") != myMap.end())
  ....

请注意,您当然可以使用您的 Store对象作为值。要将其用作 key ,您必须注意以下几点:

std::maps with user-defined types as key

对于您的具体示例,我建议您使用 std::string作为键,以及 Products 的 vector 作为值(value)。

关于c++ - 在 vector 中使用现有对象,如果 C++ 中不存在则创建新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46883158/

相关文章:

c++ - 交替使用类作为浮点指针

C 函数指针、可微函数

时间:2019-03-08 标签:c++bloombergapicorrelationId

c++ - OpenCV中两个数组的互相关

c++ - 查找 GpuMat 所在的 GPU

c++ - 在一行中创建指向值的指针

c++ - 双星号语法 & 帮助调用成员函数

c++ - 如何在C++中声明Magnitude类型?

C:从指向结构的指针访问指向结构元素的指针

c++ - 我可以在 C++ 中使用方法指针,就像在 C# 中使用委托(delegate)一样吗?