[英]Constructor for wrapper around std::vector
I'm trying to write a wrapper class with a data member std::vector. 我正在尝试用数据成员std :: vector编写一个包装类。 How should my class's default constructor look like so that I can do the following without getting out of range error:
我的类的默认构造函数应该如何显示,以便我可以执行以下操作而不会超出范围错误:
Wrapper W;
W[0] = value; //overloaded index operator, forwards to the vector
The default constructor is irrelevant. 默认构造函数是无关紧要的。 Your
operator []
needs to check whether the supplied index is out of range and make the vector bigger as necessary. 您的
operator []
需要检查提供的索引是否超出范围,并根据需要使向量更大。 (I'm assuming here that "returns reference to the vector<T>
" is a typo and you want to forward to the vector's operator[]
at some point). (我在这里假设“返回对
vector<T>
引用”是一个错字,你想在某个时候转发给向量的operator[]
)。
You have to resize the vector before accessing the element: 您必须在访问元素之前调整向量的大小:
// in the class definition
std::vector vec;
T &operator[](typename std::vector<T>::size_type idx)
{
if (idx >= vec.size()) {
vec.resize(idx + 1);
}
return vec[idx];
}
Edit: now 0
instead of i
, that's a huge typo. 编辑:现在
0
而不是i
,这是一个巨大的错字。 In that case, you can just construct a vector of size 1 in-place: 在这种情况下,您可以在原地构建一个大小为1的向量:
std::vector<T> vec = std::vector<T>(1);
public:
T &operator[](typename std::vector<T>::size_type idx)
{
return vec[idx];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.