简体   繁体   English

在向量中使用现有对象或在C ++中创建新的(如果不存在)

[英]Use existing object in vector or create new if not exists in C++

Let's assume that I have a class named Store which contains products. 我们假设我有一个名为Store的类,其中包含产品。 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. 然后我有一个二维字符串数组,其中包含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. 现在我想遍历数组,为数组中的每个商店创建Store-object,并将其产品添加到object。 So I need to use existing Store-object or create a new if there is no any with correct name yet. 所以我需要使用现有的Store-object或者如果没有任何正确的名称则创建一个新的。 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);
}

Use a std::unordered_set<Store> , where the hash type is the string name of the store. 使用std::unordered_set<Store> ,其中哈希类型是商店的字符串名称。 Using a map -like type would lead to duplicated storage of the store name (one time as a key to the map and one time inside the Store object itself). 使用类似map的类型会导致存储名称的重复存储(一次作为地图的键,一次作为Store对象本身)。

template <>
struct std::hash<Store> {
    using Store = argument_type;
    using result_type = std::size_t;
    result_type operator()(const argument_type& s) const noexcept {
       return result_type{ std::hash<std::string>{}(s._name) }();
    }
};

std::unordered_set<Store> stores;
for (int i = 0; i < 4; ++i) {
   string storeName = storeListing[i][0];
   string productName = storeListing[i][1];

   auto iter = stores.find(storeName);
   if(iter == stores.end()) iter = stores.emplace(storeName);
   iter->addProduct(productName);
}

Most likely, because you insert "Store" copies into your 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 goes out of scope at the end of the if and StorePtr is lost. newStore在if结束时超出范围而StorePtr丢失。

Try it with: 尝试使用:

storePtr = stores.back();

Or make your vector a std::vector<Store*> . 或者使你的矢量成为std::vector<Store*>

And then: 然后:

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

And of course, as the comments suggest, a std::map would be better suited here. 当然,正如评论所暗示的那样,std :: map会更适合这里。

In short, std::map stores key-value pairs. 简而言之,std :: map存储键值对。 The key would most likely be your store name, and the value the product. 密钥很可能是您的商店名称,以及产品的价值。

Quick example: 快速举例:

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())
  ....

Note, you can of course use your Store object as value. 注意,您当然可以将Store对象用作值。 To use it as key, you have to take care of a few things: 要将其用作关键,您必须处理以下事项:

std::maps with user-defined types as key std :: maps以用户定义的类型作为键

For your specific example i would suggest you use a std::string as key, and a vector of Products as value. 对于您的具体示例,我建议您使用std::string作为键,并使用Products的向量作为值。

There are a few problems in your approach. 您的方法存在一些问题。

Problem 1: 问题1:

Store has a const data member. Store有一个const数据成员。 This will make it impossible to reorder the vector of stores. 这将使得无法重新排序商店的矢量。 That needs to be corrected. 这需要纠正。

Problem 2: 问题2:

You need to point at the right Store after insertion. 插入后需要指向正确的商店。 Here's one approach: 这是一种方法:

// decompose the problem:
// first step - get a pointer (iterator) to a mutable store *in the vector*
auto locate_or_new(std::vector<Store>& stores, std::string const& storeName)
-> std::vector<Store>::iterator
{
    auto iter = std::find_if(begin(stores), end(stores),
                             [&](Store& store)
                             {
                                 return store.getName() == storeName;
                             });
    if (iter == end(stores))
    {
        iter = stores.emplace(end(stores), storeName);
    }
    return iter;
}

//
// 2 - insert the product in terms of the above function.    
auto addProduct(std::vector<Store>& stores, std::string const& storeName, std::string const& productName)
-> std::vector<Store>::iterator
{
    auto istore = locate_or_new(stores, storeName);
    istore->addProduct(productName);
    return istore;
}

Note: 注意:

Since inserting objects into a vector can cause iterator invalidation, you will need to be careful to not hold references to objects inside the vector across sections of code that could create new stores. 由于将对象插入到向量中会导致迭代器失效,因此您需要注意不要在可以创建新存储的代码段中保留向量内对象的引用。

if (storePtr == nullptr) {
        Store newStore(storeName);
        stores.push_back(newStore);
        storePtr = &newStore;
    }

Once the if ends newStore is gone and you are left with dangling pointer storePtr . 一旦if结束newStore消失了,你就会留下悬挂指针storePtr You could use an std::set<Store *> here 你可以在这里使用std::set<Store *>

std::set<Store *> myset;
Store *c = new Store("store3");
std::set<Store *>::iterator iter = myset.find(c);
if(iter!=myset.end())
{
   (*iter)->addProduct("Product1");
}
else
{
   c->addProduct("Product1");
   myset.insert(c);
}

There is a solution using vectors and iterators. 有一个使用向量和迭代器的解决方案。 Dont forget to include the "algorithm" header! 别忘了包含“算法”标题!

std::vector<Store> stores;
for (int i = 0; i < 4; ++i) {
    string storeName = storeListing[i][0];
    string productName = storeListing[i][1];

    auto storeIter = std::find_if(stores.begin(), stores.end(), [storeName](Store store) -> bool {
        return store.getName() == storeName;
    }); //Find the store in the vector

    if (storeIter == stores.end()) //If the store doesn't exists
    {
        stores.push_back(Store(storeName)); //Add the store to the vector
        storeIter = prev(stores.end()); //Get the last element from the vector
    }
    Store* storePtr = &(*storeIter); //You can convert the iterator into a pointer if you really need it
    storeIter->addProduct(productName);
    //storePtr->addProduct(productName);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM