[英]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;
*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?你也可以做
(*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;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.