标准库忽略了实现std::set
和std::map
的基本操作
set<T> set<T>::getUnion(set<T> other)
和
bool map<K,V>::contains(K key)
我知道这些方法有冗长和/或间接的解决方法,但如果我希望我的代码具有最大的可读性和表现力,我将不得不从 STL 继承,编写我自己的 Set
和 Map
类,并自己实现它们。是的,我知道反对这样做的说教,但事实是 STL 是不完整的。
我已经这样做了,但现在我无法使用例如
初始化我的新类Set<int> s = {1,2,3,4};
如何从 std
类继承这些初始化器?
最佳答案
尽管从标准库容器公开继承被认为是一个坏主意,但您可以“继承”构造函数:
template <typename T>
struct Set : std::set<T>
{
using std::set<T>::set; // "inherit" the constructors.
};
然后
Set<int> s{1,6,4,3,3,9};
请注意,更好的方法可能是实现函数:
template <typename C>
bool contains(const C& container, const typename C::key_type& key)
{
return container.count(key);
}
关于c++ - 从 std::set 或 std::map 继承初始化语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23437562/