具有固定但运行时确定长度的矢量容器(以C++为单位)

Container of vectors with fixed, but runtime-determined length in C++

本文关键字:C++ 为单位 运行时      更新时间:2023-10-16

有没有办法构造一个包含相同长度的向量的容器,但在运行时(即容器构建时间(确定此长度?

这个问题已经被问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