A mapping
maps all possible keys, so you cannot get just the values which you have explicitly added, without knowing the keys which you have explicitly used. In order to achieve that, every time you add a value, you need to store the key in an array (but ideally, only if it's the first time that you are using this key).
If you also plan to delete values from the mapping
, then you need to scan the array and delete the appropriate key, or you can establish a more sophisticated data-structure which will allow you to delete the key from the array in a constant number of operations.
For example:
pragma solidity ^0.4.24;
contract StudentManager {
uint[] public studentList;
struct Student {
bool valid;
uint index;
string name;
uint age;
bool tookTest;
}
mapping(uint => Student) public students;
/* Update or insert a student */
function upsert(uint ID, string _name, uint _age, bool _tookTest) external {
Student storage student = students[ID];
if (!student.valid) {
student.valid = true;
student.index = studentList.length;
studentList.push(ID);
}
student.name = _name;
student.age = _age;
student.tookTest = _tookTest;
}
/* Remove a student */
function remove(uint ID) external {
Student storage student = students[ID];
require(student.index < studentList.length);
require(ID == studentList[student.index]);
uint lastStudent = studentList[studentList.length - 1];
students[lastStudent].index = student.index;
studentList[student.index] = lastStudent;
studentList.length -= 1;
delete students[ID];
}
/* Get the total number of students */
function studentCount() external view returns (uint) {
return studentList.length;
}
}
mapping
maps all possible keys, so you cannot get just the values which you have explicitly added, without knowing the keys which you have explicitly used. In order to achieve that, every time you add a value, you need to store the key in an array (but ideally, only if it's the first time that you are using this key).mapping
, then you need to scan the array and delete the appropriate key (or you can establish a more sophisticated data-structure which will allow you to delete the key from the array in a constant number of operations - if you want this solution, then I've got one ready).