Hi StackOverflow community,
I am working on creating a generic container class template in C++ that can support various data structures like std::vector
std::map
, etc. My goal is to make this container flexible enough to handle different types of data structures and provide a uniform interface for operations like Add
and Remove
.
Here is the code snippet that I have so far:
With this implementation I can create a general interface for my container, but I'm specifically looking to improve the functionality of std::map. I want to be able to add and remove items for maps in two ways:
`#include <iostream>
#include <vector>
#include <map>
template <typename T>
class IContainer
{
public:
virtual void Add(const T& item) = 0; // Adds item
virtual void Remove(const T& item) = 0; // Remove the item if it exists in the container
virtual ~IContainer() = default;
};
template <typename T, typename ContainerType>
class Container : public IContainer<T>
{
public:
void Add(const T& item) override
{
container.Add(item);
}
void Remove(const T& item) override
{
container.Remove(item);
}
private:
ContainerType container;
};
template <typename T>
class VectorContainer
{
public:
void Add(const T& item)
{
vect.push_back(item);
}
void Remove(const T& item)
{
// Assuming T has a valid equality comparison
auto it = std::remove(vect.begin(), vect.end(), item);
vect.erase(it, vect.end());
}
private:
std::vector<T> vect;
};
template <typename Key, typename Value>
class MapContainer
{
public:
void Add(const std::pair<const Key, Value>& keyValue)
{
container.insert(keyValue);
}
void Add(const Key& key, const Value& value)
{
container[key] = value;
}
void Remove(const std::pair<const Key, Value>& keyValue)
{
container.erase(keyValue.first);
}
private:
std::map<Key, Value> container;
};
int main()
{
Container<int, VectorContainer<int>> myCont;
myCont.Add(1); // myCont has a generic interface thanks to IContainer
Container<std::pair<const std::string, int>, MapContainer<std::string, int>> mapCont;
mapCont.Add({"key1", 42});
mapCont.Add("key2", 88); // Using the new Add function (not working)
return 0;
}
`
Using std::pair
as a single parameter. Using separate key and value parameters. I implemented the Add method for both cases, but the container does not support separate keys and key values, so I'm not sure if this is the most efficient or correct way to achieve this flexibility. I'm also looking for suggestions to make this template more compatible with other container types.
Can someone provide insight or improvements on how to do the following:
Efficiently support both append methods for std::map. Generalize this approach to effectively cover other container types. Any advice or code sample would be greatly appreciated!
Thank you!
Aucun commentaire:
Enregistrer un commentaire