gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:34:21 27 4
gpt4 key购买 nike

假设我有一个名为 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com