I'm trying to pass a vector to a function, loop over it, and modify the values before sending it back, but I'm having a very hard time with the pointer
and reference
to make it work:
I understand that itr
is a pointer. I'm confused about resource
on the for loop
. I believe it to be a reference
, but I keep getting the error:
error: no viable overloaded '='resource = resource value
ACTION test::addto(name player){
auto itr = player.require_find(wallet.value, USER_NOT_FOUND(wallet));
asset value1 = asset(100, ACTION_SYMBOL);
asset value2 = asset(100, FOOD_SYMBOL);
changeResourceValue(itr->resources, value1);
changeResourceValue(itr->resources, value2);
player.modify(itr, _self, [&](auto& p) {
p.resources = resources;
});
}
void changeResourceValue(const vector<asset>* resources, asset value){
for (auto &resource : *resources){
if(resource.symbol == value.symbol){
resource = resource value;
}
}
}
CodePudding user response:
For starters the first parameter of the function changeResourceValue
is declared with the qualifier const
void changeResourceValue(const vector<asset>* resources, asset value){
It means that you may not change elements of the vector pointed to by the pointer resources
.
So you need at least to remove the qualifier const
.
The second problem is that the operator = is not defined for objects of the type asset
. Maybe the error message is a consequence that the variable resource
is a constant reference.
Also you need to check whether the member function require_find
returns a pointer or an iterator in this record
auto itr = player.require_find(wallet.value, USER_NOT_FOUND(wallet));
Old C versions of std::vector
defined iterators as pointers. But in new versions of std::vector
iterators are not pointers.
So maybe the function should be declared like
void changeResourceValue( std::vector<asset>::iterator resources, asset value);
CodePudding user response:
IIUC, resource
is indeed a reference, but to const asset
and not asset
because you have a (pointer to) const
vector. If you want to change a vector, don’t pretend you don’t, i.e. pass a regular, non-const pointer.