具有固定但运行时确定长度的矢量容器(以C++为单位)
Container of vectors with fixed, but runtime-determined length in C++
有没有办法构造一个包含相同长度的向量的容器,但在运行时(即容器构建时间(确定此长度?
这个问题已经被问C++:固定但运行时定义的长度数组的向量,其动机是节省内存。我的动机是不同的,我想避免潜在的错误,而不必让每个使用容器的函数首先验证所有元素的长度是否相同。
(在我的特定情况下,我使用的是std::unordered_map
,但我假设答案与容器类型无关。我也很乐意使用自定义类而不是unordered_map
如果有帮助的话(。
是的,当然可以。像往常一样,最好的解决方案是创建一个新类型,通过其接口维护您需要的不变量。
最简单的方法是简单地为子容器创建一个新类型,以确保向量的长度永远不会被修改(即不提供任何允许添加或删除元素的函数(。然后,您可以在容器容器中使用该类型,无论哪种类型。
正如在另一个答案中已经建议的那样,您可以基于std::vector
创建一个新类型(例如,通过依赖对象组合(,并且此新类型保留了您需要的不变量。
例如,请考虑以下类模板fixed_vector
:
#include <vector>
template<typename T>
class fixed_vector {
std::vector<T> vec_; // underlying vector
public:
using size_type = typename std::vector<T>::size_type;
explicit fixed_vector(size_type count): vec_(count) {}
fixed_vector(size_type count, const T& value): vec_(count, value) {}
fixed_vector(std::initializer_list<T> init): vec_(init) {}
template<typename InputIter>
fixed_vector(InputIter first, InputIter last): vec_(first, last) {}
T& operator[](size_type pos) { return vec_[pos]; }
T const& operator[](size_type pos) const { return vec_[pos]; }
size_type size() const { return vec_.size(); }
// ...
};
fixed_vector
中包含的std::vector
的大小在对象构造(即运行时(确定。通过插入或删除元素来修改fixed_vector
的大小是不可能的,因为它的接口不会公开任何底层std::vector
插入操作(例如,push_back()
(或删除操作(例如,pop_back()
(。
// vector of 10 defualt constructed elements
fixed_vector<int> a(10);
assert(a.size() == 10);
// vector of 100 floats with the value 1.5
fixed_vector<float> b(100, 1.5f);
assert(b.size() == 100);
// vector of 3 ints: 1, 2 and 3
fixed_vector<int> c{1, 2, 3};
assert(c.size() == 3);
// initialize from other container
std::vector<int> vec{1, 2, 3, 4, 5};
fixed_vector<int> d(vec.begin(), vec.end());
assert(d.size() == 5);
请注意,对fixed_size
对象的赋值操作仍可能更改其大小,例如:
fixed_vector<int> u(100), v(10); // u and v of size 100 and 10, respectively
assert(u.size() == 100); // ok
u = v;
assert(u.size() == 100); // fails! u.size() is now 10
相关文章:
- 以天C++为单位的两个时间戳之间的差异
- 如何以毫秒为单位获取开始时间和 now() 之间的毫秒差异(以 C++为单位?
- 从原始字节解码协议缓冲区(以 C++为单位)
- 如何在 c++ 中确定一条指令(以字节为单位)在哪里结束,另一条指令从哪里开始?
- 编写以 C++ 为单位返回值的函数
- 以C++为单位进行运行长度编码
- 如何找到两个日期之间的时间差异(以秒和纳秒为单位)?
- arr[n] 是否以 C++ 为单位打印数组的长度?
- 字符串数组上的 sizeof 运算符以 C++ 为单位给出不同的输出
- 以 C++ 为单位具有输出限制的排列
- 以 GDB 为单位指定浮点精度
- 整数数据如何以位为单位存储在内存中?不是右对齐吗?
- 如何在没有硬编码的情况下以C++为单位获取类数组的长度?
- 指针引用的生存期(以 C++为单位)
- 以字符为单位设置控制台大小
- 获取嵌套 stl 容器的大小(以字节为单位)
- 有没有一种 STL 方法可以找到字符串的所有排列,给出一个以 C++ 为单位的大小?
- 二进制数组中最大连续 1 的起始和结束索引,以 C++ 为单位
- 正向声明的枚举,默认值以.h为单位
- 常量"C"占用的空间(以字节为单位)