如何创建具有最大长度的向量?
How can I create a vector with a maximum length?
我想创建一个容器,它提供与 std::vector
相同的所有功能,但需要注意的是,一旦向量达到指定大小时,您就不能再添加元素。
我的第一个想法是从 std::vector
继承并做类似
的事情
template <typename T, unsigned int max>
class MyVector : public std::vector<T> {
public:
// override push_back, insert, fill constructor, etc...
// For example:
virtual void push_back(const T& var) override {
if (this.size() < max) vec.push_back(var);
}
};
但是后来才知道继承STL容器是bad.
第二个想法是创建一个包装器 class,即
template <typename T, unsigned int max>
class MyVector {
private:
std::vector<T> vec;
public:
// Wrappers for every single std::vector function...
iterator begin() { return vec.begin(); }
const_iterator begin() const { return vec.begin(); }
//and on and on and on...etc.
};
但这对我来说很难闻。看起来很难维护。
我是否遗漏了一些明显的东西,我应该尝试其他方法吗?
How can I create a vector with a maximum length?
你不能用 std::vector
做到这一点。但是,您可以在达到某个限制后避免插入任何元素。例如:
if (v.size() < 10) {
// OK, we can insert
}
I want to create a container that provides all of the same functionality as a std::vector
but with the caveat that you cannot add anymore elements once the vector reaches a specified size.
那个,你可以做到。
virtual void push_back(const T& var) override {
std::vector::push_back
不是虚拟的,因此您可能不会 override
它。
此外,我建议考虑在达到 max
的情况下是否应该默默地忽略推回。
But then I learned that inheriting STL containers is bad.
更具体地说,公开继承它们有点不稳定。
使用私有继承,您可以使用using
选择您希望直接委托的成员,并手动实现不同的成员。
Seems very difficult to maintain.
标准库不常变化,矢量 class 到目前为止变化不大,变化非常简单,所以“非常困难”是有争议的 - 虽然当然是主观的.
您可以使用元编程使其易于维护。但这可能是一种过度设计的方法。
我想创建一个容器,它提供与 std::vector
相同的所有功能,但需要注意的是,一旦向量达到指定大小时,您就不能再添加元素。
我的第一个想法是从 std::vector
继承并做类似
template <typename T, unsigned int max>
class MyVector : public std::vector<T> {
public:
// override push_back, insert, fill constructor, etc...
// For example:
virtual void push_back(const T& var) override {
if (this.size() < max) vec.push_back(var);
}
};
但是后来才知道继承STL容器是bad.
第二个想法是创建一个包装器 class,即
template <typename T, unsigned int max>
class MyVector {
private:
std::vector<T> vec;
public:
// Wrappers for every single std::vector function...
iterator begin() { return vec.begin(); }
const_iterator begin() const { return vec.begin(); }
//and on and on and on...etc.
};
但这对我来说很难闻。看起来很难维护。
我是否遗漏了一些明显的东西,我应该尝试其他方法吗?
How can I create a vector with a maximum length?
你不能用 std::vector
做到这一点。但是,您可以在达到某个限制后避免插入任何元素。例如:
if (v.size() < 10) {
// OK, we can insert
}
I want to create a container that provides all of the same functionality as a
std::vector
but with the caveat that you cannot add anymore elements once the vector reaches a specified size.
那个,你可以做到。
virtual void push_back(const T& var) override {
std::vector::push_back
不是虚拟的,因此您可能不会 override
它。
此外,我建议考虑在达到 max
的情况下是否应该默默地忽略推回。
But then I learned that inheriting STL containers is bad.
更具体地说,公开继承它们有点不稳定。
使用私有继承,您可以使用using
选择您希望直接委托的成员,并手动实现不同的成员。
Seems very difficult to maintain.
标准库不常变化,矢量 class 到目前为止变化不大,变化非常简单,所以“非常困难”是有争议的 - 虽然当然是主观的.
您可以使用元编程使其易于维护。但这可能是一种过度设计的方法。