What prevents the subclassing of vector<> and having at() or operator[] resize the array if necessary?

huangapple go评论95阅读模式
英文:

What prevents the subclassing of vector<> and having at() or operator[] resize the array if necessary?

问题

以下是翻译好的部分:

"阻止vector&lt;&gt;子类化并重写at()operator[]以根据需要调整数组大小的内容是什么?具体来说,我想让代码像这样工作:

MYvector&lt;int&gt; v;
v[3] = 1;

等效于:

vector&lt;int&gt; v;
if (v.size() &lt;= 3)
    v.resize(3 + 1);
v[3] = 1;

我多年前曾研究过这个问题,并得出结论vector&lt;&gt;根本不是为了子类化而设计的,但现在不记得主要的障碍是什么了。

明确一下,如果只需要编写一个新的虚拟方法,我会这样做,但如果随后需要编写几十个其他定义(友元函数?迭代器?),那就不值得了。

方言将是C++17或C++20,尽管对早期或后期方言或供应商方言的讨论也会很有兴趣。"

英文:

What prevents the subclassing of vector&lt;&gt; and overriding at() or operator[] to resize the array if necessary? Specifically I'd like code to work like this:

MYvector&lt;int&gt; v;
v[3] = 1;

would be equivalent to:

vector&lt;int&gt; v;
if ( v.size() &lt;= 3 )
    v.resize( 3 + 1 );
v[3] = 1;

I looked into this many years ago and concluded that vector&lt;&gt; 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 &lt;class T&gt;
class MYvector : public vector&lt;T&gt;
{
public:
    T&amp; operator[](size_t i) {if (vector&lt;T&gt;::size() &lt; i+1) vector&lt;T&gt;::resize(i+1); return vector&lt;T&gt;::operator[](i);}
    T&amp; at(size_t i) {if (vector&lt;T&gt;::size() &lt; i+1) vector&lt;T&gt;::resize(i+1); return vector&lt;T&gt;::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)

huangapple
  • 本文由 发表于 2023年8月5日 02:06:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76838261.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定