Unsolved QVector has no assign method?
-
@Publicnamer said in QVector has no assign method?:
Isn't there an automatically resized array?
As @jsulm says.
However if you really want this then (presumably, untested) you can derive fromQVector
and override the[]
operator?EDIT
I don't think you can override the[]
operator after all?
In which case it may not be as "elegant" as you might wish, but you do realize that before going[index]
you can insertif (index >= qVector.size()) qVector.resize(index);
Up to you whether you want to do this where you are using
qVector[index]
only as an l-value or also as an r-value (i.e. when writing to it versus reading from it, if I am using the wrong terminology). -
@JonB said in QVector has no assign method?:
I don't think you can override the [] operator after all?
Why not?
-
@JonB said in QVector has no assign method?:
if (index >= qVector.size())
qVector.resize(index);Yes that's what I'm doing now. It's a tiny inconvenience.
-
@jsulm said in QVector has no assign method?:
Such a thing would be extremely dangerous
Not necessarily. It depends on the use case.
-
@Publicnamer said in QVector has no assign method?:
Not necessarily. It depends on the use case.
Your example above will result in an oom exception after a few milliseconds. If you don't call this dangerous...
-
@jsulm said in QVector has no assign method?:
I don't think you can override the [] operator after all?
Because
operator[]
is listed among Public functions but does not sayvirtual
? -
@JonB said in QVector has no assign method?:
Because operator[] is listed among Public functions but does not say virtual?
unlikely you need
operator[]
to be virtual. You normally don't use base classes interfaces for containers.#include<QVector> template <class T> class ExpandingVector : public QVector<T>{ public: using QVector<T>::QVector; T& operator[](int index) { if (index >= QVector<T>::size()) QVector<T>::resize(index+1); return QVector<T>::operator[](index); } };
P.S.
There are many cases where
I still think there is no case where this is useful but you do you bro.
-
@VRonin
This is very useful, but I don't understand :)
If I use your template, but the baseopertaor[]
isn't virtual/overridable, what happens when some other code receiving my array asQVector<>
parameter, notExpandingVector<>
, and then accesses it via[]
? They won't get my oevrride if it wasn'tvirtual
? -
@JonB That's correct but 3rd party code receiving a
QVector<>
would need to stick to theQVector
contract (i.e.index
must be within bounds).ExpandingVector
will behave exactly likeQVector
in that case. -
@VRonin
Then I understand completely, thank you.You just have your own definition of
operator[]
. You might as well have defined it as afoobar()
method :) -
@Publicnamer said in QVector has no assign method?:
And yet a hash isn't good enough.
Why? Can you describe your use-case?
-
@JKSH I asked this too at the start, but no response....