简体   繁体   中英

How to assign value to vector of pair using iterator?

I would like to assign value to vector of pair using iterator.

My Code :

class MyData
{
public:
    void add(const pair<int, string *> &elem)
    {
        auto it =  find_if(myVec.begin(), myVec.end(), [&](pair<int, string *> const & ref)
                   {
                        return ref.second == elem.second;
                   });
        if (it != myVec.end()) //if found
        {
            *it->first = elem.first; //Error : indirection requires pointer operand
            return;
        }
        myVec.push_back(elem);
    }
    vector<pair<int, string *>> myVec;
};

But I'm getting the following error:

*it->first = elem.first; -> indirection requires pointer operand

How can I properly assign value to an element in a vector of pair?

without the * . Remember, the -> also does dereferencing and once you dereference the iterator, you have an object of the type it iterates over, which in this case is a pair. Your current code tries to then dereference the pair, which doesn't make sense, hence the error. You could also do (*it).first , but that's what the -> is for, so why not use it?

#include <vector>
using namespace std;

class MyData
{
public:
    void add(const pair<int, string *> &elem)
    {
        auto it =  find_if(myVec.begin(), myVec.end(), [&](pair<int, string *> const & ref)
                   {
                        return ref.second == elem.second;
                   });
        if (it != myVec.end()) //if found
        {
            it->first = elem.first; //Error : indirection requires pointer operand
            return;
        }
        myVec.push_back(elem);
    }
    vector<pair<int, string *>> myVec;
};

https://godbolt.org/z/iWneFB

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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