代码之家  ›  专栏  ›  技术社区  ›  Zack Lee

如何用迭代器给向量赋值?

  •  -1
  • Zack Lee  · 技术社区  · 6 年前

    我想赋值给向量对使用迭代器。

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

    但我得到了以下错误:

    *它->第一个=元素优先;->间接寻址需要指针操作数

    如何正确地为成对向量中的元素赋值?

    1 回复  |  直到 6 年前
        1
  •  1
  •   xaxxon    6 年前

    没有 * . 记住,那个 -> (*it).first ,但这就是 为什么不使用它呢?

    #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