英文:
What prevents the subclassing of vector<> and having at() or operator[] resize the array if necessary?
问题
以下是翻译好的部分:
"阻止vector<>
子类化并重写at()
或operator[]
以根据需要调整数组大小的内容是什么?具体来说,我想让代码像这样工作:
MYvector<int> v;
v[3] = 1;
等效于:
vector<int> v;
if (v.size() <= 3)
v.resize(3 + 1);
v[3] = 1;
我多年前曾研究过这个问题,并得出结论vector<>
根本不是为了子类化而设计的,但现在不记得主要的障碍是什么了。
明确一下,如果只需要编写一个新的虚拟方法,我会这样做,但如果随后需要编写几十个其他定义(友元函数?迭代器?),那就不值得了。
方言将是C++17或C++20,尽管对早期或后期方言或供应商方言的讨论也会很有兴趣。"
英文:
What prevents the subclassing of vector<>
and overriding at()
or operator[]
to resize the array if necessary? Specifically I'd like code to work like this:
MYvector<int> v;
v[3] = 1;
would be equivalent to:
vector<int> v;
if ( v.size() <= 3 )
v.resize( 3 + 1 );
v[3] = 1;
I looked into this many years ago and concluded that vector<>
simply wasn't designed to be subclassed, but now can't remember what the big road block was.
To be clear it's something I'd do it if were basically one new virtual method to write, but not worth doing if I then need to make dozens of other definitions (friend functions? iterators?) as well.
Dialect would be C++17 or C++20, though discussion of earlier or later dialects or vendor dialects would also be of high interest.
答案1
得分: 3
不要说废话,直接说程序
template <class T>
class MYvector : public vector<T>
{
public:
T& operator[](size_t i) {
if (vector<T>::size() < i + 1)
vector<T>::resize(i + 1);
return vector<T>::operator[](i);
}
T& at(size_t i) {
if (vector<T>::size() < i + 1)
vector<T>::resize(i + 1);
return vector<T>::at(i);
}
};
英文:
It is possible by using a class definition like this:
template <class T>
class MYvector : public vector<T>
{
public:
T& operator[](size_t i) {if (vector<T>::size() < i+1) vector<T>::resize(i+1); return vector<T>::operator[](i);}
T& at(size_t i) {if (vector<T>::size() < i+1) vector<T>::resize(i+1); return vector<T>::at(i);}
};
However, it may be better to resize the vector explicitly instead of doing it by calling operator[]
. Automatic resizing can mask errors, and also the new elements (after automatic resizing) are value-initialized by the default constructor (but not explicitly initialized by the user)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论