簡體   English   中英

如何使用迭代器為成對的向量賦值?

[英]How to assign value to vector of pair using iterator?

我想使用迭代器為對向量賦值。

我的代碼:

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

但我收到以下錯誤:

*it->first = elem.first; -> 間接需要指針操作數

如何正確地為一對向量中的元素賦值?

沒有* 請記住, ->也會取消引用,一旦您取消引用迭代器,您就會擁有一個它迭代的類型的對象,在這種情況下是一對。 您當前的代碼嘗試取消引用該對,這是沒有意義的,因此會出現錯誤。 你也可以做(*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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM