Frage

Code is below. I have a data member called book_b and within the function OB::x() this unordered_map gets objects inserted. On the first insertion the key is 10 and the new object inserted at key=10 works fine. However, when key=10 appears again, I am anticipating a new object would be created and inserted at key=10 (replacing the previous object at key=10). However, once OB::x() returns, when we are back in OB::y() it is as if the new object had never been inserted.

I thought this should work because I am passing the book_b object by pointer to the function modifying its state? I'm worried there's something wrong with my fundamental understanding.

class OB{
    public:
        void y(O lo);
        void x(std::unordered_map<int, PL>* book, int a, long b);

    private:
        std::unordered_map<int, PL> book_b;
        std::unordered_map<int, PL> book_a;
};


void OB::y(O lo){

    //Code which obtains parameters to use in x() from lo
    int a = o.getA();
    long b = o.getB();

    //This is the data member the below function will insert an object in to
    std::unordered_map<int,PL>* book = &book_b;

    //This is the function which should be changing the state of book.
    //It works on the first call (when a new object is inserted) but on repeated calls
    //(where the object may be replaced with a new object with the same key) it acts
    //as if the new key-value pair wasnt replacing the existing key-value pair.

    x(book, a, b);

}


//Works when book is empty and we insert a new PL object, however, when I go to "overwrite"
//an existing PL object with the same key (a) it doesn't hold state once the function returns

void OB::x(std::unordered_map<int,PL>* book, int a, long b){
    PL temp;
    temp.setQuantity(b);
    book->insert(std::make_pair(a, temp));
}
War es hilfreich?

Lösung

std::unordered_map::insert does not insert a new element if one with the same key already exists.

auto p = book->insert(std::make_pair(a, temp));
std::cout << std::boolalpha;
std::cout << "Did insert succeed? " << p.second << std::endl;

If you want to update an existing element if one exists, use operator[]:

(*book)[a] = temp;

Note: you don't need to pass pointers, unless you want to allow for the possibility of nullptr being passed. It is simpler to use references:

void OB::x(std::unordered_map<int,PL>& book, int a, long b) { ... }

x(book_b, a, b);

Andere Tipps

std::unordered_map::insert "inserts element(s) into the container, if the container doesn't already contain an element with an equivalent key."

Change

book->insert(std::make_pair(a, temp));

to

(*book)[a] = temp;

and also note that passing by reference instead of pointer would be more reasonable here and make your code much cleaner :)

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top