I would love to get a pointer to a QVector
element so I can use that object elsewhere however the at()
method gives me a const T&
value and the operator[]
gives me a T&
value.
I'm confused on how to use these to get a pointer so that I will use the same object instead of using a copy constructor.
A T&
value is not a copy, it is a reference.
References look a lot like pointers : they are light, and can be used to modify the underlying object. Only, you use them with the same syntax as direct objects (with dots instead of arrows), and some other differences you may want to check out in the article.
To edit an object currently inside the Vector, you can use for instance vector[i].action();
. This will call the action() method from the object inside the vector, not on a copy. You can also hand over the reference to other functions (provided they take reference arguments), and they will still point to the same object.
You can also get the adress of the object from a reference : Object* pObject = & vector[i];
and use it as any pointer.
If you really need pointers to objects, you can also use a Vector of pointers : QVector<Object*> vector;
However, this requires you to handle creation / destruction, which you don't need with a Vector of objects.
Now, if you want a pointer to the Vector itself, just do QVector<Object> *pVector = &vector;
QVector::operator[]
returns a reference to the element at the given index. A reference is modifiable if it isn't a const reference, what is returned by QVector::at()
.
You can simply modify the element by assigning a new value or using a modifying member of the object, like in the following examples:
// vector of primitive types:
QVector<int> vector;
vector.append(3);
vector.append(5);
vector.append(7);
vector[0] = 2; // vector[0] is now 2
vector[1]++; // vector[1] is now 6
vector[2] -= 4; // vector[2] is now 3
// vector of objects:
QVector<QString> strings;
strings.append(QString("test"));
strings[0].append("ing"); // strings[0] is now "testing"
QMap
and QHash
even support operator[]
for non-existing keys, which makes the folliowing possible:
QMap<int, int> map;
map[0] = 4;
map[3] = 5;
One disadvantage of operator[]
is that the entry gets created if it didn't exist before:
// before: map contains entries with key 0 and 3
int myEntry = map[2]; // myEntry is now 0
// after: map contains entries with keys 0, 2 and 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With