I write a class with a structure and with some methods which will work with multimap. The addItemToList-method will add a structure in multimap and saveListData-method will store it on a binary file:
class listData
{
public:
struct ItemStruct
{
long int item_id;
int ess_id;
char item_type;
char list_type;
time_t add_date;
};
int addItemToList(long int item_id, char list_type, char item_type = '\0', int ess_id = 0)
{
ItemStruct *pAddingItem = new ItemStruct;
pAddingItem->item_id = item_id;
pAddingItem->list_type = list_type;
pAddingItem->item_type = item_type;
pAddingItem->ess_id = ess_id;
pAddingItem->add_date = std::time(nullptr);
typedef std::multimap<char, struct ItemStruct> ListDataMap;
static ListDataMap container;
container.insert(std::pair<char, struct ItemStruct>(list_type, *pAddingItem));
return 0;
}
int saveListData()
{
// how can I access to data stored in the container static variable?
return 0;
}
};
and the next code for use the class:
#include <ctime>
#include <iostream>
#include <map>
#include "lists.cpp"
using namespace std;
int main(int argc, char** argv)
{
listData test;
test.addItemToList(10, 's', 'm', 1555);
test.addItemToList(10, 'c', 'm', 1558);
test.saveListData();
}
How can I access to data stored in the container static variable?
In your code, you have declared your multimap at the local scope of the method addItemToList
, not at class scope. When you want to access it in various methods of your class, you have to declare and define it at class scope.
Additionally, I've adjusted the content of your addItemToList
implementation to avoid a memory leak.
For simplicity, I put everything in a single file:
#include <ctime>
#include <iostream>
#include <map>
using namespace std;
class listData
{
private:
struct ItemStruct
{
long int item_id;
int ess_id;
char item_type;
char list_type;
time_t add_date;
};
typedef std::multimap<char, struct ItemStruct> ListDataMap;
static ListDataMap container; // multimap declaration
public:
int addItemToList(long int item_id, char list_type, char item_type = '\0', int ess_id = 0)
{
ItemStruct pAddingItem;
pAddingItem.item_id = item_id;
pAddingItem.list_type = list_type;
pAddingItem.item_type = item_type;
pAddingItem.ess_id = ess_id;
pAddingItem.add_date = std::time(nullptr);
container.insert(std::pair<char, struct ItemStruct>(list_type, pAddingItem));
return 0;
}
int saveListData()
{
// use container here
// container.<whatever-method>
return 0;
}
};
listData::ListDataMap listData::container; // multimap definition
int main(int argc, char** argv)
{
listData test;
test.addItemToList(10, 's', 'm', 1555);
test.addItemToList(10, 'c', 'm', 1558);
test.saveListData();
}