Overview
This how-to provides instructions to delete from Key-Value Map
(kv map
) based on the unique key.
Before you begin
Make sure you have the following prerequisites in place:
- An EOSIO development environment, for details consult the Get Started Guide
- A smart contract named
smrtcontract
- A user defined type,
struct
orclass
, which defines the data stored in the map, namedperson
- A
kv map
object, namemy_map
, which stores objects of typeperson
, with unique keys of typeint
Refer to the following reference implementation for your starting point:
smartcontract.hpp file
struct person {
eosio::name account_name;
std::string first_name;
std::string last_name;
};
class [[eosio::contract]] smartcontract : public eosio::contract {
using my_map_t = eosio::kv::map<"kvmap"_n, int, person>;
public:
using contract::contract;
smartcontract(eosio::name receiver, eosio::name code, eosio::datastream<const char*> ds)
: contract(receiver, code, ds) {}
private:
my_map_t my_map{};
};
Procedure
Complete the following steps to delete a person
object with a given ID from the kv map
, and print an informative message otherwise:
- Create a new action in your contract, named
delete
, which takes as input parameters the person ID. - Use the
find()
function defined for thekv::map
type, with the give ID as parameter, to find theperson
which is to be deleted. - If the
person
with the give ID is found use theerase()
function defined for thekv::map
, with the given ID as parameter, to erase the person object from the map. - If the
person
with the given ID is not found print an informative error message.
Refer to the following reference implementation to delete a person
object from the kv map
:
smartcontract.hpp file
struct person {
eosio::name account_name;
std::string first_name;
std::string last_name;
};
class [[eosio::contract]] smartcontract : public eosio::contract {
using my_map_t = eosio::kv::map<"kvmap"_n, int, person>;
public:
using contract::contract;
smartcontract(eosio::name receiver, eosio::name code, eosio::datastream<const char*> ds)
: contract(receiver, code, ds) {}
// deletes a person based on unique id
[[eosio::action]]
void del(int id);
private:
my_map_t my_map{};
};
smartcontract.cpp file
// deletes a person based on unique id
[[eosio::action]]
void kv_map::delete(int id) {
// search for person based on unique id
auto itr = my_map.find(id);
// check if person was found
if (itr != my_map.end()) {
// extract person from iterator and delete it
const auto person_found = itr->second();
// delete it from kv::map
my_map.erase(id);
eosio::print_f("Person (%, %, %) was successfully deleted.",
person_found.first_name, person_found.last_name, person_found.personal_id);
}
else {
eosio::print_f("Person with ID % not found.", id);
}
}
Summary
In conclusion, the above instructions show how to delete from Key-Value Map
(kv map
) based on the unique key.